开发者

Repositories, UnitOfWork and Unity

开发者 https://www.devze.com 2023-03-25 15:20 出处:网络
Using Unity when I \'new up\' an object that requires dependencies i.e. Repositories, UnitOfWork all is great, my new object gets the dependencies injected and the \'newed\' up object has control over

Using Unity when I 'new up' an object that requires dependencies i.e. Repositories, UnitOfWork all is great, my new object gets the dependencies injected and the 'newed' up object has control over the UnitOfWork, the repositories as they also require a UnitOfWork dependency get injected too, with the same UnitOfWork (using PerResolve lifetime manager).

All's good, however where I have an issue is the scope of this UnitOfWork and Repositories are at the class level.

What if I would like the lifetime of the UnitOfWork to be controlled at the method level, how should I approach this ?? Should I be using m开发者_开发问答ethod injection ? If so should my method be taking all the required dependencies i.e. Repositories and UnitOfWork again ??

Some guidance would be greatly appreciated.


Actually, Keep unit of work (wrap with DbContext) per request basis. If you use method wise it will be a costly solution. For example,

public void SaveAccount(Account account)
{
    using(var unitOfWork = unitOfFactory.CreateUnitofWork())
    {
       new Repository<Account>(unitOfWork).Attach(account);
       unitOfWork.Commit();           
    }       
}

public Account GetAccount(int id)
{
    using(var unitOfWork = unitOfFactory.CreateUnitofWork())
    {
      return new Repository<Account>(unitOfWork).Get(id);
    }
}

public void MakePayment(int fromAccount, int toAccount, decimal ammount)
{
   var from = Dao.GetAccount(fromAccount);
   var to = Dao.GetAccount(toAccount);
   from.Total -= amount;
   to.Total += amount;
   Dao.SaveAccount(from);
   Dao.SaveAccount(to);
}

We are using 4 different connections to the database in a single method also not safe use of transactions. User per request base unit of work can as a container you can use HttPContext.


You shouldn't be using DI for method parameter, at least not directly.

The usual approach is to have an IUnitOfWorkFactory or some such. Get that out of the container. Then in your method call the factory to get your unit of work object. The factory may (or may not) go back to the container to do it's work.


Having a search on StackOverflow seems to suggest to pull the Http Request Lifetime Manager from the MVC project here:

http://mvcunity.codeplex.com/

Since Unity itself does not have it's own Http Request Lifetime Manager.

Other Questions:

How to inject dependencies per http request (or per http context) with unity 2.0 and asp.net mvc

Using ASP.NET Session for Lifetime Management (Unity)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号