[英]How to register and resolve open generic with two type arguments as interface with one type argument using Autofac
我有许多带有两个类型参数的具体泛型类,它们实现了一个类型参数的泛型接口。 例如:
public interface ISomeService<T>
{
// ...
}
public class SomeService<TA, TB> : ISomeService<TA>
{
// ...
}
我使用Autofac像这样注册它们:
var containerBuilder = new ContainerBuilder();
containerBuilder.RegisterGeneric(typeof(SomeService<,>))
.As(typeof(ISomeService<>))
.InstancePerLifetimeScope();
var container = containerBuilder.Build();
尝试像这样解析ISomeService<Foo>
的实例时:
var service = container.Resolve<ISomeService<Foo>>();
我收到一个Autofac.Core.Registration.ComponentNotRegisteredException
异常,表明所请求的服务ISomeService`1[[Foo]]
尚未注册。
使用Simple Injector,可以使注册部分封闭的通用类型如下:
container.Register(typeof(ISomeService<>),
typeof(SomeService<,>).MakeGenericType(
typeof(SomeService<,>).GetGenericArguments().First(),
typeof(Bar)),
Lifestyle.Scoped);
没有其他DI库可以处理此问题,但是在这种情况下,对于Autofac这样的容器有一个简单的解决方法; 您可以简单地从以下类型派生:
public class BarSomeService<TA> : SomeService<TA, Bar>
{
public BarSomeService([dependencies]) : base([dependencies]) { }
}
containerBuilder.RegisterGeneric(typeof(BarSomeService<>))
.As(typeof(ISomeService<>))
.InstancePerLifetimeScope();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.