[英]Autofac decorating open generics registered using assembly scanning
我正在嘗試將autofac裝飾器支持功能應用到我的場景中,但沒有成功。 看起來在我的情況下,它沒有正確地為注冊分配名稱。
有沒有辦法用名稱注冊掃描的程序集類型,以便我以后可以在開放的通用裝飾器鍵中使用它?
或者也許我完全錯了,在這里做一些不合適的事情?
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()
只是KeyedService
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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.