這裏是我的情況:溫莎登記通用命令/命令處理程序
public static class DomainCommandProcessor
{
public static void Dispatch<T>(T command) where T : IDomainCommand
{
var serviceLocator = ServiceLocator.Current;
var handler = serviceLocator.GetInstance<IDomainCommandHandler<T>>();
if (handler != null)
handler.Handle(command);
}
}
public class FakeGenericCommand<T1, T2> : IDomainCommand
{
public FakeGenericCommand(T1 first, T2 second)
{
First = first;
Second = second;
}
public T1 First { get; private set; }
public T2 Second { get; private set; }
}
public class FakeGenericCommandHandler<T1, T2> : IDomainCommandHandler<FakeGenericCommand<T1, T2>>
{
public void Handle(FakeGenericCommand<T1, T2> command)
{
// something interesting
}
}
用法:
DomainCommandProcessor.Dispatch(new FakeGenericCommand<string, string>("hi", "there"))
我不能讓溫莎註冊權。下面的作品非常適合我所有的非通用命令:
container.Register(Classes.FromAssemblyNamed(namespaceName)
.BasedOn(typeof(IDomainCommandHandler<>))
.WithService.AllInterfaces()
.LifestyleTransient());
如果我直接註冊的每個可能的實現,它的工作原理,但顯然是次優:
container.Register(
Component.For<IDomainCommandHandler<FakeGenericCommand<string, string>>>()
.UsingFactoryMethod(input => new FakeGenericCommandHandler<string, string>())
.LifestyleTransient());
建議?
由於您正在使用DI庫,是否有任何令人信服的理由讓您訴諸服務位置而不是使用依賴注入?將這個靜態'DomainCommandProcessor'比注入需要它的組件的'IDomainCommandProcessor'有什麼優勢? – Steven 2014-09-23 19:18:45