共享的工作单元的许多服务在ASP.NET MVC中3 [英] Sharing a Unit of Work among many Services in ASP.NET MVC 3

查看:54
本文介绍了共享的工作单元的许多服务在ASP.NET MVC中3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的控制器使用2个或更多的服务。反过来,我的服务,建造和消耗自己的工作类的单位的实例(与访问库)。

我想我的服务共享工作实例的同一个单位,并使其单元测试。我的问题是:


  1. 我应该注入工作和服务的单位到我的控制器?

  2. 我需要工作单元注入到我的服务好。哪里
    我应该怎么办呢?谢谢你这么多。


解决方案

1)我不认为在UI控制器注入工作单位是一个好主意,试图从UI逻辑和交易分开。

2)是的,你可以在你的服务preferable注入UOW通过IoC容器注入的构造函数。一些人设计,它是一个静态的工厂,但我preFER用它作为构造注入参数

 公共类为MyService:IMyService
{
  IUnitOfWork _unitOfWork;  公共则将MyService(IUnitOfWork UOW)
  {
    _unitOfWork = UOW;
  }  公共无效DoSomeOperation(SampleParam参数)
  {
    _unitOfWork.BeginTrx();
    // 做一些工作
    _unitOfWork.Commit();
  }
}

或者使用静态工厂

 公共类为MyService:IMyService
{
  公共无效DoSomeOperation(SampleParam参数)
  {
    使用(UnitOfWork.Start())
    {
      // 做一些工作
    }
  }
}

my controllers use 2 or more services. In turn, my services construct and consume their own instance of a Unit of Work class (with access to the repositories).

I would like my services to share a same Unit of Work instance, and make it unit-testable. My questions are:

  1. Should I inject the Unit of Work and services to my controllers?
  2. I would need to inject the Unit of Work to my services as well. Where should I do that? Thank you so much.

解决方案

1) I dont think injecting Unit of Work in UI controller is a good idea, try to separate the logic and transaction from the UI.

2) Yes you can inject UoW in your service preferable as a constructor injected through IoC container. some people design it to be a static factory but i prefer use it as parameter injected in constructor

public class MyService : IMyService
{
  IUnitOfWork _unitOfWork;

  public MyService(IUnitOfWork uow)
  {
    _unitOfWork = uow;
  }

  public void DoSomeOperation(SampleParam param)
  {
    _unitOfWork.BeginTrx();
    //  do some work 
    _unitOfWork.Commit();
  }
}

or using static factory

public class MyService : IMyService
{
  public void DoSomeOperation(SampleParam param)
  {
    using(UnitOfWork.Start())
    {
      //  do some work 
    }
  }
}

这篇关于共享的工作单元的许多服务在ASP.NET MVC中3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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