c# - 简单的注入(inject)器如何针对同一接口(interface)注册/解析单例集合

标签 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; }
}

这就是我在简单注入(inject)器中用来注册集合的东西

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

No registration for type IEnumerable<IEnumerable<IGlobalExchangeRateLimitProvider>> could be found.

我的意思是我能猜到这是为什么,这是因为我目前注册的是一个IEnumerable<Registration>。不是 IEnumerable<IGlobalExchangeRateLimitProvider>

但我只是不确定如何连接 SimpleInjector 以提供我在这里想要的东西。我需要做什么才能注册以上内容并获得 IEnumerable<IGlobalExchangeRateLimitProvider>从容器中取出?

如何使用 SimpleInjector 实现此目的?

最佳答案

你打错了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();

关于c# - 简单的注入(inject)器如何针对同一接口(interface)注册/解析单例集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52777116/

相关文章:

c# - ASP.NET 核心 Web API : Authorization based on permissions from database

c# - 自动缩进关闭

.net - 带有结构图 2.6 的装饰器模式

.net - 如何告诉 StructureMap 3 为特定类型使用特定的构造函数?

c# - 如何解析工厂在简单注入(inject)器中创建的对象的装饰器

c# - transient 组件注册为 transient 但实现了 idisposable

c# - 我如何使用 NServiceBus 做竞争消费者

c# - 是否可以使用 NSubstitute 模拟本地方法变量?

java - Micronaut - Springframework @Bean 等效项是什么?

c# - Simple Injector 和默认的 AccountContoller 依赖问题