我在应用程序中有一些处理程序类,根据传递的枚举值在运行时创建。它看起来像这样:
public interface IMyHandler
{
void Handle();
}
public class SimpleHandler : IMyHandler
{
public void Handle()
{
//logic here...
}
}
public class ComplexHandler : IMyHandler
{
public void Handle()
{
//logic here...
}
}
public enum HandlerTypes
{
Simple,
Complex
}
public class Hanlderfactory
{
public IMyHandler CreateHandler(HandlerTypes type)
{
switch(type)
{
case HandlerTypes.Simple:
return new SimpleHandler();
case HandlerTypes.Complex:
return new ComplexHandler();
default:
throw new NotSupportedException();
}
}
}
对我来说没问题。但是如果我想像这样在我的处理程序中注入一些组件,就会出现一个问题:
public class SimpleHandler : IMyHandler
{
public SimpleHandler(IComponentOne c1, IComponentTwo c2, IComponentThree c3)
{
//...
}
public void Handle()
{
//logic here...
}
}
我使用Unity IoC容器,当然希望在此处使用它。但是手动调用
Resolve
方法看起来很丑陋。我走错路了吗?如何优雅地将这两种模式结合起来使用?在工厂内部调用IoC容器是唯一的选择吗?更新:我尝试使用
InjectionFactory
类的委托注入。它运行良好。但在这种情况下,如果我需要在两个应用程序中使用此工厂逻辑,则需要在两个应用程序的启动中注册此委托和枚举与类之间的映射。var container = new UnityContainer();
container.RegisterType<IMyHandler, SimpleHandler>(HandlerTypes.Simple.ToString());
container.RegisterType<IMyHandler, ComplexHandler>(HandlerTypes.Complex.ToString());
container.RegisterType<Func<HandlerTypes, IMyHandler>>(new InjectionFactory(c => new Func<HandlerTypes, IMyHandler>(type => c.Resolve<IMyHandler>(type.ToString()))));
public class Handler : IHandlerService<IComplexHandler>
Unity可以解析类型参数。 - Aydin