单个 ASP.NET MVC 项目中的多个 IUnitOfWork 实现
我们有一个使用 Unity 和 IUnitOfWork 作为 EF 上下文的站点。到目前为止,我们只使用了一个 EF Context,因此这是 Unity 配置中映射的一个。这一切都是通过构造函数注入来处理的,这是我们希望保持一致性的事情。
现在,我们为站点内使用的 PaymentController
引入了另一个 EF 上下文,但 Unity 配置当前仅允许我们为 IUnitOfWork 创建一种类型。
我知道我可以为具有不同名称属性的新上下文创建一个新的
元素,但如何在控制器构造函数中实现这一点以使用名为 payment 的元素?
<register type="IUnitOfWork" mapTo="FirstContext" />
<register type="IUnitOfWork" mapTo="PaymentsContext" name="payments"/>
public class PaymentController()
{
public PaymentController(IUnitOfWork unitOfWork)
{
//How to I tell unity that this needs to be a payments
_unitOfWork = unitOfWork;
}
}
非常感谢
We have a site using Unity and IUnitOfWork for our EF context. Until now we've only been using a single EF Context so this is the one mapped in Unity config. This has all been handled through constructor injection and this is something we'd like to maintain for consistency.
We've now introduced another EF Context for our PaymentController
that is used within the site but Unity config currently only allows us to create one type for IUnitOfWork.
I know that I can create a new <register/>
element for the new context with a distinct name attribute but how do I implement this within the controller constructor to use the one named payments?
<register type="IUnitOfWork" mapTo="FirstContext" />
<register type="IUnitOfWork" mapTo="PaymentsContext" name="payments"/>
public class PaymentController()
{
public PaymentController(IUnitOfWork unitOfWork)
{
//How to I tell unity that this needs to be a payments
_unitOfWork = unitOfWork;
}
}
Many Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当 FirstContext 和 PaymentsContext 各自具有一组唯一的实体(例如,每个实体都连接到不同的数据库)时,值得在代码中显式定义它。做到这一点的一种方法是为每个工作单元指定一个工厂:
不仅使您的依赖关系非常清晰(因为您知道代码正在处理什么类型的上下文),而且还简化了 DI 配置,因为您赢得了不需要任何命名注册。
When the
FirstContext
andPaymentsContext
have each an unique set of entities (for instance, each connect to a different database) it is worth wild to explicitly define this in code. One way of doing this is by specifying a factory for each unit of work:Not only makes this your dependencies very clear (because you know what type of context the code is dealing with), but it also simplifies the DI configuration, because you won't need any named registrations.