0

I've configured my IoC Container, Unity to resolve my IDbContext an EntityFramwork DbContext in the constructor of my unit of work.

I'm wondering if that is best practices or if I'm just getting in a future headaches of non disposed DbContext. This is an ASP.Net MVC application so there will be a lot of short-life containers. The lifetime of each container is per request

Any advice?

public class UnitOfWork : IUnitOfWork
{
    private readonly IDbContext context;

    public UnitOfWork(IDbContext context)
    {
        this.context = context;
    }
}

public class SampleService : ISampleService
{
    private readonly IUnitOfWork unitOfWork;

    public SampleService(IUnitOfWork unitOfWork)
    {
        this.unitOfWork = unitOfWork;
    }
}
Alexandre Rondeau
  • 2,667
  • 24
  • 31
  • Related: http://stackoverflow.com/questions/10585478/one-dbcontext-per-web-request-why – Steven Dec 23 '13 at 23:46
  • You should certainly not build one container per request, because this can have severe negative impact on the performance of your app and the complexity of your configuration. Using Unity's child container feature is fine though, although often still unneeded and performance heavy. – Steven Jan 12 '14 at 02:55
  • The IoC container is not by request, the IoC container is build one time as if the same for the lifecycle of the application. My `DbContext` is per request, so each service call will have only one IUnitOfWork, so all the same DbContext. Each service call is considered single-thread. – Alexandre Rondeau Jan 12 '14 at 03:08

2 Answers2

1

Having IDbContext managed by the container, and set to PerRequest lifetime is the best practice. You code looks clean and may easily be managed by an IoC container.

As @Steven linked to, the normal practice is to use the unit or work and dispose immediately.

If the Unity IoC container can be properly configured to dispose the IDbContext at the end of request, it is best. In some cases with ASP.NET, you may have to do disposal in Application_EndRequest()

Community
  • 1
  • 1
Raul Nohea Goodness
  • 2,549
  • 23
  • 24
1

I think your solution is fine, though there is a warning about using the per request lifetime manager in the Unity documentation: Per Request Lifetime Management. I think as long as you know what you are doing, you are using that lifetime manager just as it was intended. Another option you could use is creating a base controller and implementing IDisposable on that controller. MVC will call dispose on a controller at the very end of a request, so you could dispose of any objects that way too.

mmilleruva
  • 2,110
  • 18
  • 20