用于开放通用的Autofac注册提供程序

时间:2016-08-25 05:26:45

标签: c# generics dependency-injection inversion-of-control 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 个答案:

答案 0 :(得分:1)

正如@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>>获取所有可用的实施,然后根据需要选择正确的服务。

相关问题