Simple Injector - RegisterAll注册在构造函数中注入空集合

时间:2013-07-15 18:39:30

标签: c# .net dependency-injection simple-injector

我有以下工厂:

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>();

为什么我的工厂无法解决服务集合?

1 个答案:

答案 0 :(得分: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