[英]Autofac register provider for open generic
我有一個通用接口的兩種實現。
public class ConcreteComponent1<T>:IService<T>{}
public class ConcreteComponent2<T>:IService<T>{}
我有一家工廠將創建適當的具體實現。
public class ServiceFactory
{
public IService<T> CreateService<T>()
{
//choose the right concrete component and create it
}
}
我已經注冊了以下服務使用者,它將使用該服務。
public class Consumer
{
public Consumer(IService<Token> token){}
}
我不確定如何使用autofac注冊開放式通用服務的提供程序。 任何幫助表示贊賞。 提前致謝。
正如@Steven所說,我也建議不要使用工廠。 相反,您可以將IService<T>
注冊為命名服務或鍵服務 ,然后在Consumer
類的構造函數中確定要使用的實現:
containerBuilder.RegisterGeneric(typeof(ConcreteComponent1<>)).Named("ConcreteComponent1", typeof(IService<>));
containerBuilder.RegisterGeneric(typeof(ConcreteComponent2<>)).Named("ConcreteComponent2", typeof(IService<>));
containerBuilder.RegisterType<Consumer>();
然后,您可以使用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"];
}
}
另外,如果您不想命名服務,也可以通過注入IEnumerable<IService<Token>>
來獲取所有可用的實現,然后根據需要選擇正確的服務。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.