【发布时间】:2010-11-18 09:47:03
【问题描述】:
我有一个包含 3 种不同实现的接口。我使用 Unity Container 在 Web 应用程序的 Web.config 中将 3 个实现注册为命名别名。
有没有一种方法可以使用 Unity,根据某些逻辑来解析其中一个注册实例。逻辑包括联系数据库以决定要解决的实现。
感谢您的帮助。
问候 比拉尔
【问题讨论】:
标签: unity-container ioc-container containers
我有一个包含 3 种不同实现的接口。我使用 Unity Container 在 Web 应用程序的 Web.config 中将 3 个实现注册为命名别名。
有没有一种方法可以使用 Unity,根据某些逻辑来解析其中一个注册实例。逻辑包括联系数据库以决定要解决的实现。
感谢您的帮助。
问候 比拉尔
【问题讨论】:
标签: unity-container ioc-container containers
您可以在抽象工厂中实现逻辑并将其注入:
public interface IMyInterface { }
public interface IMyInterfaceFactory {
IMyInterface GetMyInterface();
}
public class MyInterfaceFactory : IMyInterfaceFactory {
private readonly IUnityContainer _container;
public MyInterfaceFactory(IUnityContainer container) {
_container = container; }
IMyInterface GetMyInterface() {
var impName = Get_implementation_name_from_db();
return container.Resolve<IMyInterface>(impName);
}
}
【讨论】:
您可以创建一个“路由器”实现,它知道如何将请求路由到其他实现之一:
// Here is a possible implementation of the router. There are
// of course many ways to do this.
public class MyRouterImpl : IMyInterface
{
List<IMyInterface> implementations = new List<IMyInterface>();
public MyRouterImpl(MyImpl1 i1, MyImpl2 i2, MyImpl3 i3)
{
this.implementations.Add(i1);
this.implementations.Add(i2);
this.implementations.Add(i3);
}
void IMyInterface.Method()
{
int indexOfImplementationToExecute =
GetIndexOfImplementationToExecute();
IMyInterface impl =
this.implementations[indexOfImplementationToExecute];
impl.Method();
}
}
【讨论】: