假设一个简单的接口:解决自动工厂通用类型
public interface ICommandHandler<T> { void Handle(T command); }
假定为不同的混凝土
T
小号若干实施方式,如:public class FooCommandHandler : ICommandHandler<FooCommand> { /*...*/ }
假设一个通用的工厂该接口的实现:
public class FactoryCommandHandler<T> : ICommandHandler<T> { public FactoryCommandHandler(Func<ICommandHandler<T>> factory) { /*...*/ } /*...*/ }
现在,我要注册从工厂处理程序是当ICommandHandler<T>
解决该解决的实例。
我的问题是,我无法正确注册其他实现,所以他们的工厂可以解决。
这里是我的尝试:
builder.RegisterAssemblyTypes(assembly)
.Where(type => type.Name.EndsWith("CommandHandler"))
.Named("concreteCommandHandler", typeof(ICommandHandler<>));
builder.RegisterGeneric(typeof(FactoryCommandHandler<>)
.WithParameter(
(p, c) => true,
(p, c) => c.ResolveNamed("concreteCommandHandler", p.ParameterType))
.As(typeof(ICommandHandler<>));
然而,这种失败,因为没有登记名为Func<ICommandHandler<SomeConcreteCommand>>
。在这种情况下,Autofac似乎无法自动创建工厂,which it normally supports。
如何解决注册并实现我的目标?
“FooCommand”对象的实现是什么?它有父母吗?如果确实如此,则可以尝试通过修改“公共类FactoryCommandHandler:ICommandHandler 其中T:[parentclassname]” –
@AzharKhorasany:它没有基类。而且我不明白你建议的通用类型约束是如何改变的。 –
应用一个约束告诉编译器T的对象只能是一个具体的类型,并且它应该能够在没有约束的情况下注册到编译器不知道什么是T. –