5

我正在尝试将 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");
4

2 回答 2

13

这是一个尝试,不在 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;
于 2011-11-16T03:51:18.937 回答
3

如果您想清理您的注册代码,您还可以定义以下附加扩展方法(非常冗长并且基于其他重载的 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();
于 2013-09-19T23:54:45.183 回答