假設一個簡單的接口:解決自動工廠通用類型
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. –