2014-11-25 91 views
1

我的控制器使用DI引用我的服务。控制器不知道EF或其DbContext。即使是服务没有EF或的DbContext的知识,因为它们引用UOW(也可以通过DI):如何在WebApi中处理DbContext?

public class CustomerController : ApiController 
{ 
    private readonly ICustomerService customerService; 

    public CustomerController(ILogService logService, 
           ICustomerService customerService) 
    { 
     this.customerService = customerService; 
    } 
} 

public CustomerService(ILogService logService, IUnitOfWork unitOfWork) {} 

的UOW明显引用的DbContext:

public interface IUnitOfWork : IDisposable { } 

public class UnitOfWork : IUnitOfWork 
{ 
    private DbContext context; 
} 

问题:

  1. UoW是否应该实现IDisposable,以便在UoW超出范围后处理上下文?

  2. 服务是否应该实现IDisposable来处置UoW?或者是处置由Autofac(我的DI)处理的UoW和服务?

+0

也许这个链接将帮助你:http://codereview.stackexchange.com/questions/47879/unit-of-work-and-repository-with-entity-framework-6/47904#47904 – 2014-11-25 11:25:46

+0

问题1:是的,我认为这是做到这一点的最佳方式。 – 2014-12-04 13:03:06

回答

0

你总是需要,让你从垃圾收集器(GC)带负载断开后自己清理,避免GC做清洁的你,因为它是昂贵的,并且需要额外的时间/资源。

因此,如果您的对象拥有一个资源,并且您的对象在对象本身超出范围或处置时不会处理该资源,那么这是内存泄漏,除非其他人会跟踪该资源并处理它。

现在取决于您注册服务的哪个生命周期,Uow和上下文,DI可能会调用您的对象的dispose方法,这意味着您的对象需要实现IDisposable。

我将在每个实现IDisposable,并确保我注册我的服务,这是根对象,我将注册与“实例每生存期范围”,这将创建一个单一的实例每个http请求,并将调用然而,如果你注册了“Instance Per Dependency”,那么你有责任处理这个实例,这意味着你需要重写ApiController的dispose方法,并从服务开始处理周期在上下文中。

希望有所帮助。