如何根据传递到的服务来解析接口

And*_*i M 26 c# autofac

我有一个界面.

public interface ISomeInterface {...}
Run Code Online (Sandbox Code Playgroud)

和两个实现(SomeImpl1和SomeImpl2):

public class SomeImpl1 : ISomeInterface {...}
public class SomeImpl2 : ISomeInterface {...}
Run Code Online (Sandbox Code Playgroud)

我也有两个服务,我注入ISomeInterface(通过contructor):

public class Service1 : IService1 
{
   public Service1(ISomeInterface someInterface)
   {
   }
...
}
Run Code Online (Sandbox Code Playgroud)

public class Service2 : IService2 
{
   public Service2(ISomeInterface someInterface)
   {
   }
...
}
Run Code Online (Sandbox Code Playgroud)

我正在使用Autofac作为我的IoC工具.这个问题.如何配置Autofac注册,以便SomeImpl1自动注入Service1,SomeImpl2将自动注入Service2.

谢谢!

ben*_*ruk 33

Autofac支持按名称识别服务.使用此功能,您可以使用名称注册实现(使用Named扩展方法).然后,您可以使用ResolveNamed扩展方法在IServiceX注册委托中按名称解析它们.以下代码演示了这一点.

var cb = new ContainerBuilder();
cb.Register(c => new SomeImpl1()).Named<ISomeInterface>("impl1");
cb.Register(c => new SomeImpl2()).Named<ISomeInterface>("impl2");
cb.Register(c => new Service1(c.ResolveNamed<ISomeInterface>("impl1"))).As<IService1>();
cb.Register(c => new Service2(c.ResolveNamed<ISomeInterface>("impl2"))).As<IService2>();
var container = cb.Build();

var s1 = container.Resolve<IService1>();//Contains impl1
var s2 = container.Resolve<IService2>();//Contains impl2
Run Code Online (Sandbox Code Playgroud)

替代使用RegisterType(相对于Register)

您可以使用达到同样的效果RegisterType相结合扩展方法与WithParameterResolvedParameter.如果采用命名参数的构造函数还采用您在注册委托中无需指定的其他非命名参数,这将非常有用:

var cb = new ContainerBuilder();
cb.RegisterType<SomeImpl1>().Named<ISomeInterface>("impl1");
cb.RegisterType<SomeImpl2>().Named<ISomeInterface>("impl2");
cb.RegisterType<Service1>().As<IService1>().WithParameter(ResolvedParameter.ForNamed<ISomeInterface>("impl1"));
cb.RegisterType<Service2>().As<IService2>().WithParameter(ResolvedParameter.ForNamed<ISomeInterface>("impl2"));
var container = cb.Build();

var s1 = container.Resolve<IService1>();//Contains impl1
var s2 = container.Resolve<IService2>();//Contains impl2
Run Code Online (Sandbox Code Playgroud)