0

私は次の工場を持っています:

public class MyFactory : IMyFactory
{
    private readonly IEnumerable<IMyService> myServices

    public MyFactory(IEnumerable<IMyService> myServices)
    {   
        this.myServices = myServices;
    }
}

私はIEnumerable<IMyService>このように登録しています:

container.Register<IMyFactory, MyFactory>();

container.RegisterAll<IMyService>(
    from s in AppDomain.CurrentDomain.GetAssemblies()
    from type in s.GetExportedTypes()
    where !type.IsAbstract
    where typeof(IMyService).IsAssignableFrom(type)
    select type);

container.Verify();

次に、次の結果が得られます

// correctly resolves to count of my 4 implementations 
// of IMyService
var myServices = container.GetAllInstances<IMyService>();

// incorrectly resolves IEnumerable<IMyService> to count 
// of 0 IMyServices.
var myFactory = container.GetInstance<IMyFactory>();

ファクトリがサービスのコレクションを解決できないのはなぜですか?

4

1 に答える 1

1

次のコンソール アプリケーションを作成しました。

using System;
using System.Collections.Generic;
using System.Linq;
using SimpleInjector;

public interface IMyManager { }
public interface IMyFactory { }
public interface IMyService { }

public class MyManager : IMyManager
{
    public MyManager(IMyFactory factory) { }
}

public class MyFactory : IMyFactory
{
    public MyFactory(
        IEnumerable<IMyService> services)
    {
        Console.WriteLine("MyFactory(Count: {0})",
            services.Count());
    }
}

public class Service1 : IMyService { }
public class Service2 : IMyService { }
public class Service3 : IMyService { }
public class Service4 : IMyService { }

class Program
{
    static void Main(string[] args)
    {
        var container = new Container();

        container.Register<IMyFactory, MyFactory>(); 
        container.Register<IMyManager, MyManager>(); 

        container.RegisterAll<IMyService>(
            from nd in AppDomain.CurrentDomain.GetAssemblies()
            from type in nd.GetExportedTypes()
            where !type.IsAbstract 
            where typeof(IMyService).IsAssignableFrom(type) 
            select type); 

        var myManager = container.GetInstance<IMyManager>();

        Console.WriteLine("IMyService count: " + 
            container.GetAllInstances<IMyService>().Count());
    }
}

実行すると、次のように出力されます。

MyFactory(カウント: 4) IMyService カウント: 4

于 2013-07-16T08:38:55.270 に答える