Ninject + WCF + Nhibernate +工作单元

时间:2016-05-02 06:51:31

标签: nhibernate ninject unit-of-work

我有以下实现。 我的服务需要注入一个unitOfWork实例,它还需要不同的存储库(在我的例子中是CustomerRepo和ManagerRepo)。

基本上,UnitOfWork的一个实例需要注入每个服务类(我有多个服务类),并且需要将相同的实例注入存储库,因此可以一次完成并提交多个存储库的事务。如何实现这一目标?

像 服务 - > UnitOfWork(服务)向所有存储库注入' A'服务使用

B服务 - > UnitOfWork(B服务)向所有存储库注入' B'服务使用

不要担心语法,这只是一个伪代码。

public class MyCustomService : ICustomService {
    private IUnitOfWork _unitOfWork;
    private ICustomerRepository _customeRepo;
    private IManagerRepositor _managerRepo;


    public MyCustomService(IUnitOfWork uow, ICustomerRepository customeRepo, IManagerRepositor managerRepo){
        _unitOfWork = uow;
        _customerRepo = customerRepo;
        _managerRepo = managerRepo;
    }

    public void UpdateCustomer(int customerId, int managerId){

        try{
            _unitOfWork.BeginTransaction();

            _customerRepo.UpdateCustomer(customerId,managerId);
            _managerRepo.UpdateManager(customerId,managerId);

            _unitOfWork.Commit();
        }
        catch (Exception) {
            _unitOfWork.Rollback();
        }
    }
}
public class CustomerRepository : ICustomerRepository 
{
    private IUnitOfWork _unitOfWork;

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

    public void UpdateCustomer(int customerId, int managerId){
        _unitOfWork.OpenSession();
        var customerObj = _UnitOfWork.Session.Get<Customer>(customerId);    
        customerObj.ManagerId = managerId;
        _UnitOfWork.Session.SaveOrUpdate(customerObj);
    }
}
public class UnitOfWork : IUnitOfWork{
    private readOnly ISessionFactory SessionFactory; //singleton

    protected ISession Session {get;set;}
    private ITransaction _transaction;

    public UnitOfWork(ISessionFactory sessionFactory){
        SessionFactory = sessionFactory;
    }

    public void OpenSession(){
        if(this.Session == null){
            this.Session = this.SessionFactory.OpenSession();
            this.Session.FlushMode = FlushMode.Auto;
        }
    }

    public void BeginTransaction(){
        //Opens a new transaction
        if(_transaction == null){
            this._transaction = this.Session.BeginTransaction();
        }
    }

    public void Commit(){
        //Commits transaction
        this._transaction.Commit();
    }

    public void Rollback(){
        this._transaction.Rollback();
    }
}

如何将存储的UOW实例注入存储库?

0 个答案:

没有答案