C# AutoFac RegisterGenericDecorator不使用具有类型约束的decorator
我有一个具有许多具体实现的通用命令处理程序C# AutoFac RegisterGenericDecorator不使用具有类型约束的decorator,c#,autofac,C#,Autofac,我有一个具有许多具体实现的通用命令处理程序 public interface ICommandHandler<TCommand> 公共接口ICommandHandler 我有一个带有类型约束的装饰器,我想用于ICommandHandler的多个(但不是全部)实现 public class AddNoteCommandHandlerDecorator<TCommand> : ICommandHandler<TCommand> where T
public interface ICommandHandler<TCommand>
公共接口ICommandHandler
我有一个带有类型约束的装饰器,我想用于ICommandHandler的多个(但不是全部)实现
public class AddNoteCommandHandlerDecorator<TCommand>
: ICommandHandler<TCommand> where TCommand : INoteCommand
{
private readonly ICommandHandler<TCommand> decorated;
public AddNoteCommandHandlerDecorator(ICommandHandler<TCommand> decorated)
{
this.decorated = decorated;
}
public void Handle(TCommand command)
...
公共类AddNoteCommandHandlerDecorator
:ICommandHandler,其中TCommand:INoteCommand
{
私有只读ICommandHandler;
公共AddNoteCommandHandlerDecorator(ICommandHandler装饰)
{
这是装饰过的;
}
公共无效句柄(TCommand命令)
...
我正在尝试按如下方式向AutoFac注册:
public static void Register(HttpConfiguration config)
{
var builder = new ContainerBuilder();
builder.RegisterControllers(typeof(MvcApplication).Assembly);
var assemblies = AppDomain.CurrentDomain.GetAssemblies();
builder.RegisterAssemblyTypes(assemblies)
.As(t => t.GetInterfaces()
.Where(a => a.IsClosedTypeOf(typeof(ICommandHandler<>)))
.Select(a => new KeyedService("commandHandler", a)));
builder.RegisterGenericDecorator(
typeof(AddNoteCommandHandlerDecorator<>),
typeof(ICommandHandler<>),
fromKey: "commandHandler");
var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
config.DependencyResolver = new AutoFacContainer(new AutofacDependencyResolver(container));
}
公共静态无效寄存器(HttpConfiguration配置)
{
var builder=new ContainerBuilder();
注册控制器(类型化(MVCAPApplication).Assembly);
var assemblies=AppDomain.CurrentDomain.GetAssemblies();
builder.RegisterAssemblyTypes(程序集)
.As(t=>t.GetInterfaces()
。其中(a=>a.IsClosedTypeOf(typeof(ICommandHandler)))
.Select(a=>newkeyedservice(“commandHandler”,a));
builder.RegisterGenericDecorator(
类型(AddNoteCommandHandlerDecorator),
类型(ICommandHandler),
fromKey:“commandHandler”);
var container=builder.Build();
SetResolver(新的AutofacDependencyResolver(容器));
config.DependencyResolver=新的AutoFacContainer(新的AutofacDependencyResolver(容器));
}
但是,当对实现INoteCommand的命令调用具体的命令处理程序时,decorator不起作用
我是否在AutoFac中错误配置了注册?或者我遗漏了其他内容?您没有错误配置任何内容。AutoFac不支持开箱即用。谢谢,Steven。查看您的一些帖子,SimpleInjector是否具有该功能?如果没有,您能否提出更好的方法?是的,Simple Injector可以开箱即用。Th您无需做任何特殊操作。只需注册装饰程序;它将有条件地自动应用。好消息!我将切换到SimpleInjector。这将对您有所帮助