我有一个接口(interface),例如 ISomeService
。 ISomeService
提供通用服务,但实现可能会有所不同。因此,它们将具有不同的依赖关系。
考虑:
interface ISomeService
{
void DoSomething();
}
class SomeServiceA : ISomeService
{
public SomeServiceA(DependencyOne one, DependencyTwo two)
{
}
public void DoSomething()
{
}
}
class SomeServiceB : ISomeService
{
public SomeServiceB(DependencyThree three)
{
}
public void DoSomething()
{
}
}
现在,现实情况是我不能只将对 ISomeService 的依赖项添加到我的 Controller 并完成它。我需要根据用户告诉我的内容选择 IService 的实现,并且我可能必须为他们选择的服务创建多个副本。
也许我有一个类允许我按类型解析我需要的 ISomeService 实例:
class SomeServiceProvider
{
public T Get<T>()
where T : ISomeService
{
// uh oh, this is starting to have a bad smell... do I call the container? that's no good
}
}
所以我可以
class SomeController
{
SomeServiceProvider ServiceProvider { get; set; }
public SomeController(ServiceProvider provider)
{ ServiceProvider = provider; }
public void SomeAction(string serviceName)
{
ISomeService someService;
if (serviceName.Equals('SomeServiceA')) someService = ServiceProvider.Get<SomeServiceA>();
else someService = ServiceProvider.Get<SomeServiceB>();
someService.DoSomething();
}
}
似乎 Autofac 的委托(delegate)工厂在这里不合适,我不确定该怎么做(除了使用服务定位器)。有什么建议吗?
最佳答案
这是您需要的吗? Service types, names and keys
Services can be further identified using a service name. Using this technique, the Named() registration method replaces As().
builder.Register<OnlineState>().Named<IDeviceState>("online");
To retrieve a named service, the ResolveNamed() method is used:
var r = container.ResolveNamed<IDeviceState>("online");
关于c# - 在 Autofac 中实现通用服务工厂或提供者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3765353/