多个UnitOfWorks,ISession和存储库 [英] Multiple UnitOfWorks, ISession and repositories

查看:91
本文介绍了多个UnitOfWorks,ISession和存储库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您知道某个地方的好例子吗?

Do you know a good example somewhere for this?

我想要的是以下内容:

using(IUnitOfWork uow = UnitOfWork.Start())
{
    repositoryA.Add(insanceOfA);
    repositoryB.Add(instanceOfB);

    uow.Commit();
}

但是这种情况太理想了,因为我还想要多个UnitOfWorks(在大多数情况下是每个演示者,对于Web应用程序,不是).在那种情况下,如果我没有明确给他们类似的信息,那么存储库将如何知道要使用哪个UnitOfWork

But this case is too ideal, because what I also want is multiple UnitOfWorks (per presenter in most cases, and this is not for a web app). In that case, how will repositories know which UnitOfWork to use if I don't give them that explicitly like

repository.UnitOfWork = uow;

我的目标是让每个UnitOfWork后面都包含一个ISession,因此每个演示者一个UOW,每个演示者一个ISession.注意:我知道ISession本质上是UOW,但是我必须以这种方式进行...

My goal is to have every UnitOfWork contain a ISession behind, so one UOW per presenter, one ISession per presenter. Note: I know that ISession is esentially UOW, but I must proceed this way...

任何建议都值得赞赏

推荐答案

我要做的是将应该用于存储库的unitOfWork传递.

What I do, is pass the unitOfWork that should be used to the Repository.

要实现此目的,您可以确保必须在存储库的构造函数中传递该存储库必须使用的UnitOfWork实例.

To achieve this, you can make sure that you have to pass the UnitOfWork instance that must be used by the repository in the repository's constructor.

为了使所有操作变得更加友好,您可以在UnitOfWork上创建特定于您的项目的扩展方法(假设您的UnitOfWork是通用的并且在多个项目中使用),如下所示:

In order to make it all a bit more user-friendly, you can create extension methods on your UnitOfWork that are specific for your project (supposing that your UnitOfWork is generic and used in multiple projects) that look like this:

public static class UnitOfWorkExtensions
{
    public static IRepositoryA GetRepositoryA( this UnitOfWork uow )
    {
         return new RepositoryA(uow);
    }

    public static IRepositoryB GetRepositoryB( this UnitOfWork uow )
    {
         return new RepositoryB(uow);
    }
}

然后,它使您可以执行此操作:

Then, it enables you to do this:

using(IUnitOfWork uow = UnitOfWork.Start())
{
    var repositoryA = uow.GetRepositoryA();
    var repositoryB = uow.GetRepositoryB();

    repositoryA.Add(insanceOfA);
    repositoryB.Add(instanceOfB);

    uow.Commit();
}

这篇关于多个UnitOfWorks,ISession和存储库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆