所以我有这个类,我想关闭多个单例,我想在其中使用“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>();
出现以下错误
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
的集合实例,将鼠标悬停在经过验证的容器上时可以看到:
相反,在调用 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/