0

Now I use UnitOfWork:

class UnitOfWork:DbContext,IUnitOfWork
{
....
}

I use it in my service classes in this maner:

using(var uow = new UnitOfWork)
{
     var service = new Service(uow,new Repository<SomeClass>(uow));
     service.DoSomething();

}

I want to inject UnitOfWork to service constructor. And i make desctop app. How to do it and how UnitOfWork would be disposed?

Asher
  • 1

1 Answers1

0
public class MyService {

    Func<IUnitOfWork> _dbFunc;

    public MyService(Func<IUnitOfWork> makeDbFunc) {
        _dbFunc = makeDbFunc;
    }

    public void MyServiceCall(){

        using(var disposableDb = (IDisposable)_dbFunc()){
            // Do Work Here
        }
    } 
}

Usage:

MyService service = new MyService(() => new UnitOfWork());
service.MyServiceCall();  // <- UnitOfWork is created inside this method

You still have to create a new IUnitOfWork in your service methods. But this is a way to inject the concrete type that you will use.

Keith Payne
  • 3,002
  • 16
  • 30
  • I want to use IoC how to implement this with DI and IoC(Uniti). – Asher Aug 07 '13 at 15:10
  • And how I can dispose UnitOfWork,wich was created by ioc - container? – Asher Aug 07 '13 at 15:11
  • See http://stackoverflow.com/questions/10585478/one-dbcontext-per-web-request-why?lq=1 to understand the benefits and pitfalls of injecting the `UnitOfWork` with a container such as Unity. – Keith Payne Aug 07 '13 at 16:39