如何实例化工作单元
我正在使用依赖注入模式来解析我的 UnitOfWork 的正确实例。 当我只使用一种类型映射时,一切都好
unityContainer.RegisterType<IUnitOfWork, UnitOfWork>();
当我对同一接口使用两种类型映射时,就会出现问题:
unityContainer.RegisterType<IUnitOfWork, UnitOfWork1>();
unityContainer.RegisterType<IUnitOfWork, UnitOfWork2>();
我有非常常见的代码,可以进行如下调用
var unitOfWork = ServiceLocator.GetInstance<IUnitOfWork>();
:在某些情况下,它应该返回 UnitOfWork,在某些情况下,它应该返回工作单元2。
如何在不重构公共部分的情况下解决这个问题?
PS 是的 - 我知道命名容器))
I am using Dependency Injection pattern to resolve correct instance of mine UnitOfWork.
When I am using only one type mapping, all is ok
unityContainer.RegisterType<IUnitOfWork, UnitOfWork>();
The problem occurs when I am using two type mappings for the same interface:
unityContainer.RegisterType<IUnitOfWork, UnitOfWork1>();
unityContainer.RegisterType<IUnitOfWork, UnitOfWork2>();
I have very common code that making a call like
var unitOfWork = ServiceLocator.GetInstance<IUnitOfWork>();
In some cases it should return UnitOfWork, in some cases it should return UnitOfWork2.
How I resolve this problem without refactoring of common part?
P.S. And yes - I Know about named containers ))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用命名实例而不是命名容器。您可以像这样向 Unity 注册命名实例:
然后,要解析正确的实例,您可以使用以下语法:
另一种选择是使用某个接口(例如 IUnitOfWork2)装饰另一个 UnitOfWork 类。然后将 UnitOfWork2 注册到 IUnitOfWork2 并在需要时通过该新接口解析实例。
尽管您提到您不想重构 ServiceLocator.GetInstance 方法。我仍然认为最简单的方法是向 GetInstance 方法添加一个可选参数并使用命名实例。如果这是不可能的,您也许可以向 IUnitOfWork 注册一个工厂类,并使用它来获取正确的 UnitOfWork 实现。以下是关于如何向 Unity 注册工厂的简短指南。请注意,最新版本的 Unity 可能有不同的方法来执行此操作。另外,这里有一个来自 Stack Overflow 的问题,该问题涉及 Unity 容器和工厂。
You could use named instances instead of named containers. You can register a named instance with Unity like this:
Then, to resolve the correct instance, you can use the following syntax:
Another option is to decorate your another UnitOfWork-class with some interface (for example IUnitOfWork2). Then register UnitOfWork2 to IUnitOfWork2 and resolve the instance by that new interface when needed.
Though you mention that you don't want to refactor the ServiceLocator.GetInstance-method. I still think that the easiest way would be to add an optional parameter to the GetInstance-method and use the named instances. If that is out of question, you could perhaps register a factory-class to IUnitOfWork and use that to get the correct UnitOfWork-implementation. Here's a short guide on how to register a factory with Unity. Please note that latest version of Unity may have a different way of doing this. Also, here's a question from Stack Overflow which deals with Unity containers and factories.