Autofac在封闭类型上应用通用装饰器无法工作

时间:2016-10-04 20:32:22

标签: c# autofac mediatr

使用Autofac 3.5和MediatR,我试图将装饰器应用于实现特定接口的闭合类型。我有以下处理程序类型:

class ABCQueryHandler: IRequestHandler<GetBankStatementLinesQuery, BankStatementLine> 

我想将以下通用开放装饰器类型应用于实现IRequestHandler&lt;,&gt;的所有类型:

class LoggingHandler<TRequest, TResponse> : IRequestHandler<TRequest, TResponse> 
    where TRequest : IRequest<TResponse>

我的Autofac配置是:

builder
    .RegisterAssemblyTypes(Assembly.GetExecutingAssembly())
    .As(type => type.GetInterfaces()
        .Where(t => t.IsClosedTypeOf(typeof(IRequestHandler<,>)))
        .Select(t => new KeyedService("requestHandler", typeof(IRequestHandler<,>))))
    .InstancePerLifetimeScope();

builder.RegisterGenericDecorator(typeof(LoggingHandler<,>), typeof(IRequestHandler<,>), fromKey: "requestHandler")
    .InstancePerLifetimeScope();

关闭类型被注入,但从未使用LoggingHandler进行修饰。我不知道我在这里缺少什么,根据How to register an open generic decorator for an open generic registration in Autofac?AutoFac - Registering a decorator for some of an open Generic尝试了几种方法,但没有一种方法适用于我。

1 个答案:

答案 0 :(得分:3)

您正在将开放泛型类型传递给KeyedService。您应该按如下方式传递closed-generic类型:

builder
    .RegisterAssemblyTypes(Assembly.GetExecutingAssembly())
    .As(type => type.GetInterfaces()
        .Where(t => t.IsClosedTypeOf(typeof(IRequestHandler<,>)))
        .Select(t => new KeyedService("requestHandler", t)))
    .InstancePerLifetimeScope();