我已经阅读了几个比我需要的更复杂的例子,而且我很难将其提炼成一个简单,简洁的模式。
假设我有一个接口名称ICustomService和ICustomService的多个实现。我还有一个类Consumer,需要在运行时根据参数确定要使用哪个ICustomService。
所以我按如下方式创建一个类:
public class Consumer
{
private CustomServiceFactory customServiceFactory;
public Consumer(CustomServiceFactory _customServiceFactory)
{
customServiceFactory = _customServiceFactory;
}
public void Execute(string parameter)
{
ICustomService Service = customServiceFactory.GetService(parameter);
Service.DoSomething();
}
}
public class CustomServiceFactory
{
private IComponentContext context;
public CustomServiceFactory(IComponentContext _context)
{
context = _context;
}
public ICustomService GetService(string p)
{
return context.Resolve<ICustomService>(p); // not correct
}
}
public class ServiceA : ICustomService
{
public void DoSomething()
{
}
}
public class ServiceB : ICustomService
{
public void DoSomething()
{
}
}
让我的工厂实现接口是否有优势?如何修复我的工厂并使用Autofac注册这些类,以便Consumer.Execute(&#34; A&#34;)调用WorkerA上的DoSomething,而Consumer.Execute(&#34; B&#34;)调用WorkerB上的DoSomething?
谢谢
答案 0 :(得分:1)
您可以使用密钥注册ICustomService
的实施。例如:
builder.RegisterType<FooService>.Keyed<ICustomService>("someKey");
builder.RegisterType<BarService>.Keyed<ICustomService>("anotherKey");
然后你的工厂方法是:
public ICustomService GetService(string p)
{
return context.ResolveKeyed<ICustomService>(p);
}
但是,您可以更进一步,将CustomServiceFactory
与IComponentContext
分开:
public class CustomServiceFactory
{
private Func<string, ICustomService> _create;
public CustomServiceFactory(Func<string, ICustomService> create)
{
_create = create;
}
public ICustomService GetService(string p)
{
return _create(p);
}
}
你会这样注册:
builder.Register(c => {
var ctx = c.Resolve<IComponentContext>();
return new CustomServiceFactory(key => ctx.ResolveKeyed<ICustomService>(key));
});
在这一点上,假设CustomServiceFactory没有为该问题省略的任何其他行为,那么您也可以直接使用并注册Func<string, ICustomService>
。