简单的注入器如何针对同一接口注册/解决单例集合

时间:2018-10-12 10:02:53

标签: c# inversion-of-control simple-injector

所以我有一个我想注册多个单例的类,在这里我想使用“ ExchangeName”属性在它们之间进行区分(从容器中解析之后)

public interface IGlobalExchangeRateLimitProvider
{
    void DoSomethingWithDb();
    string ExchangeName { get; }
}

public class GlobalExchangeRateLimitProvider : IGlobalExchangeRateLimitProvider
{
    private object _syncLock = new object();

    public GlobalExchangeRateLimitProvider(string exchangeName)
    {
        ExchangeName = exchangeName;
    }

    public void DoSomethingWithDb()
    {
        lock (_syncLock)
        {

        }
    }

    public string ExchangeName { get; }
}

这就是我在简单注入器中用于注册集合的东西

var container = new Container();
container.Collection.Register(new[]
{
    Lifestyle.Singleton.CreateRegistration<IGlobalExchangeRateLimitProvider>(
        () => new GlobalExchangeRateLimitProvider("A"), container),
    Lifestyle.Singleton.CreateRegistration<IGlobalExchangeRateLimitProvider>(
        () => new GlobalExchangeRateLimitProvider("B"), container)
});
container.Verify();

这一切看起来很酷

但是当我尝试解决这样的问题

var globalExchangeRateLimitProviders =
    container.GetAllInstances<IGlobalExchangeRateLimitProvider>();

我收到以下错误

enter image description here

  

找不到类型IEnumerable >的注册。

我的意思是我可以猜测为什么会这样,这是由于我当前注册的是IEnumerable<Registration>而不是IEnumerable<IGlobalExchangeRateLimitProvider>

但是我只是不确定如何连接SimpleInjector来给我我想要的东西。为了注册上述内容并从容器中取出IEnumerable<IGlobalExchangeRateLimitProvider>,我需要做什么?

如何使用SimpleInjector做到这一点?

1 个答案:

答案 0 :(得分:3)

您正在调用错误的Register<T>重载。您实际上是在呼叫Register<T>(params T[] singletons),而不是在呼叫Register<T>(IEnumerable<Registration> registrations)。这导致注册以Registration实例的集合而不是IGlobalExchangeRateLimitProvider实例的集合的形式进行注册,就像将鼠标悬停在经过验证的容器上一样:

Simple Injector's debug view showing the root registrations

相反,在调用Collection.Register

时包括集合的类型
var container = new Container();
container.Collection.Register<IGlobalExchangeRateLimitProvider>(new[]
    {
        Lifestyle.Singleton.CreateRegistration<IGlobalExchangeRateLimitProvider>(
            () => new GlobalExchangeRateLimitProvider("A"), container),
        Lifestyle.Singleton.CreateRegistration<IGlobalExchangeRateLimitProvider>(
            () => new GlobalExchangeRateLimitProvider("B"), container)
    });
container.Verify();