Entity Framework DbContext UnitOfWork Repository IoC

604 Views Asked by At

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?

1

There are 1 best solutions below

3
Keith Payne On
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.