简体   繁体   中英

Entity Framework DbContext UnitOfWork Repository IoC

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM