我试图将自动装饰器支持功能应用到我的场景中,但没有成功。看起来在我的情况下,它没有正确地为注册分配名称。
是否有一种方法可以用名称注册扫描的程序集类型,以便我以后可以在打开的通用装饰键中使用它?
或者我完全错了,做了一些不合适的事情?builder.RegisterAssemblyTypes(typeof(IAggregateRepositoryAssembly).Assembly)
.AsClosedTypesOf(typeof(IAggregateViewRepository<>)) //here I need name, probably
.Named("view-implementor", typeof(IAggregateViewRepository<>))
.SingleInstance();
builder.RegisterGenericDecorator(typeof(CachedAggregateViewRepository<>),
typeof(IAggregateViewRepository<>), fromKey: "view-implementor");
这里有一个尝试,不是在Visual Studio前面,所以重载分辨率可能不完全正确:
builder.RegisterAssemblyTypes(typeof(IAggregateRepositoryAssembly).Assembly)
.As(t => t.GetInterfaces()
.Where(i => i.IsClosedTypeOf(typeof(IAggregateViewRepository<>))
.Select(i => new KeyedService("view-implementor", i))
.Cast<Service>())
.SingleInstance();
-
Named()
只是Keyed()
的语法糖,它将组分与KeyedService
相关联 -
As()
接收Func<Type, IEnumerable<Service>>
您还需要:
using Autofac;
using Autofac.Core;
如果您想要清理您的注册代码,您还可以定义以下额外的扩展方法(非常冗长,并且基于其他重载的autofac源,但它只需要定义一次):
using Autofac;
using Autofac.Builder;
using Autofac.Core;
using Autofac.Features.Scanning;
public static class AutoFacExtensions
{
public static IRegistrationBuilder<TLimit, TScanningActivatorData, TRegistrationStyle>
AsClosedTypesOf<TLimit, TScanningActivatorData, TRegistrationStyle>(
this IRegistrationBuilder<TLimit, TScanningActivatorData, TRegistrationStyle> registration,
Type openGenericServiceType,
object key)
where TScanningActivatorData : ScanningActivatorData
{
if (openGenericServiceType == null) throw new ArgumentNullException("openGenericServiceType");
return registration.As(t =>
new[] { t }
.Concat(t.GetInterfaces())
.Where(i => i.IsClosedTypeOf(openGenericServiceType))
.Select(i => new KeyedService(key, i)));
}
}
这将允许你简单地这样做:
builder.RegisterAssemblyTypes(typeof(IAggregateRepositoryAssembly).Assembly)
.AsClosedTypesOf(typeof(IAggregateViewRepository<>), "view-implementor")
.SingleInstance();