0

我有两个通用接口的实现。Autofac注册提供程序的开放式通用

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注册开放式通用服务的提供者。任何帮助赞赏。提前致谢。

+1

“我有一个工厂,它会创建适当的具体实现。” [不要使用工厂;这是一种代码味道](https://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=100)。 – Steven

回答

0

As @Steven说我也建议不要使用工厂。相反,你可以注册IService<T>named or keyed service,然后在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>>得到所有可用的实现和你喜欢的,然后选择正确的服务。