gpt4 book ai didi

c# - 如何根据传递到的服务解析接口(interface)

转载 作者:IT王子 更新时间:2023-10-29 04:21:38 25 4
gpt4 key购买 nike

我有一个接口(interface)。

public interface ISomeInterface {...}

和两个实现(SomeImpl1 和 SomeImpl2):

public class SomeImpl1 : ISomeInterface {...}
public class SomeImpl2 : ISomeInterface {...}

我还有两个服务,我在其中注入(inject)了 ISomeInterface(通过构造函数):

public class Service1 : IService1 
{
public Service1(ISomeInterface someInterface)
{
}
...
}

public class Service2 : IService2 
{
public Service2(ISomeInterface someInterface)
{
}
...
}

我使用 Autofac 作为我的 IoC 工具。问题。如何配置 Autofac 注册,以便 SomeImpl1 自动注入(inject)到 Service1 中,而 SomeImpl2 将自动注入(inject)到 Service2 中。

谢谢!

最佳答案

Autofac 支持 identification of services by name .使用它,您可以使用名称注册您的实现(使用 Named 扩展方法)。然后,您可以使用 ResolveNamed 扩展方法在 IServiceX 注册委托(delegate)中按名称解析它们。以下代码演示了这一点。

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

使用 RegisterType 的替代方法(相对于 Register)

您可以将 RegisterType 扩展方法与 WithParameterResolvedParameter 结合使用来获得相同的结果。如果采用命名参数的构造函数还采用您不关心在注册委托(delegate)中指定的其他非命名参数,这将很有用:

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

关于c# - 如何根据传递到的服务解析接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6262704/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com