[英]Autofac register provider for open generic
I have two implementations of a generic interface. 我有一个通用接口的两种实现。
public class ConcreteComponent1<T>:IService<T>{}
public class ConcreteComponent2<T>:IService<T>{}
I have a factory which will create the proper concrete implementation. 我有一家工厂将创建适当的具体实现。
public class ServiceFactory
{
public IService<T> CreateService<T>()
{
//choose the right concrete component and create it
}
}
I have a registered the below service consumer which will consume the service. 我已经注册了以下服务使用者,它将使用该服务。
public class Consumer
{
public Consumer(IService<Token> token){}
}
I am not sure how to register a provider for open generic service with autofac. 我不确定如何使用autofac注册开放式通用服务的提供程序。 Any help appreciated. 任何帮助表示赞赏。 Thanks in advance. 提前致谢。
As @Steven said I would also recommend against using a factory. 正如@Steven所说,我也建议不要使用工厂。 Instead you could register your IService<T>
as named or keyed service and then decide in the constructor of the Consumer
class which implementation you want to use: 相反,您可以将IService<T>
注册为命名服务或键服务 ,然后在Consumer
类的构造函数中确定要使用的实现:
containerBuilder.RegisterGeneric(typeof(ConcreteComponent1<>)).Named("ConcreteComponent1", typeof(IService<>));
containerBuilder.RegisterGeneric(typeof(ConcreteComponent2<>)).Named("ConcreteComponent2", typeof(IService<>));
containerBuilder.RegisterType<Consumer>();
Then you can use the IIndex<K,V>
class to get all the named implementations of your IService<T>
class: 然后,您可以使用IIndex<K,V>
类获取IService<T>
类的所有命名实现:
public class Consumer
{
private readonly IService<Token> _token;
public Consumer(IIndex<string, IService<Token>> tokenServices)
{
// select the correct service
_token = tokenServices["ConcreteComponent1"];
}
}
Alternatively if you don't want to name your services you can also get all available implementations by injecting IEnumerable<IService<Token>>
and then choose the correct service however you like. 另外,如果您不想命名服务,也可以通过注入IEnumerable<IService<Token>>
来获取所有可用的实现,然后根据需要选择正确的服务。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.