0

I am using Unity and Entity Framework in a Web API 2 application. I register types with the HierarchicalLifetimeManager.

var container = new UnityContainer();
container.RegisterType<IService, Service>(new HierarchicalLifetimeManager());

Do I need to wrap all my dbContext calls in a using statement like this? Is this needed? I thought Unity will dispose the context for me.

using (var client = new dbContext())
{
     var result = client.Customers.toList();
}

Or can I just use dbContext without the using statement?

Programmer
  • 121,791
  • 22
  • 236
  • 328
duyn9uyen
  • 9,585
  • 12
  • 43
  • 54

1 Answers1

0

Do I need to wrap all my dbContext calls in a using statement like this?

I would say that it depends on how you use your context. Take this example:

public class Service : IService, IDisposable
{
    private DbContext _context;
    public Service(DbContext context)
    {
        _context = context;
    }

    public object Get(int id)
    {
        return _context.Customers.Find(id);
    }

    public object Update(object obj)
    {
        // Code for updating
    }

    public void Dispose()
    {
        _context.Dispose();
    }
}

If you register Service with HierarchicalLifetimeManager the context will practially never be disposed, since nothing will dispose the service and thus never dispose the context. However, the example above should work fine with TransientLifetimeManager.

From MSDN:

HierarchicalLifetimeManager. For this lifetime manager, as for the ContainerControlledLifetimeManager, Unity returns the same instance of the registered type or object each time you call the Resolve or ResolveAll method or when the dependency mechanism injects instances into other classes.

If you instead dispose it in each method, then it will be correctly disposed regardless of what lifetimemanager you use. Also, the consumer of IService doesn't need to care about disposing IService.

public class Service : IService
{

    public object Get(int id)
    {
        using (var context = new DbContext())
        {
            return context.Customers.Find(id);
        }
    }

    public object Update(object obj)
    {
        // Code for updating
    }
}

Also, consider what happens if your Service was Transient, and is injected in a manager that is ContainerController. Since the manager never is disposed, neither is the service. The manager will keep the same instance of the service throughout the lifetime of the container. Therefore I personally suggest that you keep the disposing of the context outside of the containers control. It can work very well with the help of lifetimemanagers if you make sure that you have a chain of disposings. There are several posts here and on codereview that show examples of UoW with Unity to dispose the context.

Community
  • 1
  • 1
smoksnes
  • 10,509
  • 4
  • 49
  • 74