I am using ASP.Net MVC 4, EF and Unity for DI. The UnitOfWork template is also used. Trying to find the best way to implement this. I have a code as shown below. The problem I ran into is Dispose () in the Business and Repository layer, which is never called, only the Destructor call, so the objects never seem to be deleted. Answer the following
I really need an IDisposable implementation at the Business and Repository level (if Unity already takes care of this)
What should I do to get the Dispose () call (should I add it to the Controller too, and also delete all other objects or use a specific LifeTime manager)
I must use each instance of Singleton or dispose of it in each request, as it is in the web environment.
Global.asax.cs:
private static IUnityContainer _unityContainer; protected void Application_Start() { _unityContainer = UnityBootstrapper.SetupUnity(); _unityContainer.RegisterType<IController, ProductController>("Product"); DependencyResolver.SetResolver(new Microsoft.Practices.Unity.Mvc.UnityDependencyResolver(_unityContainer)); }
UnityBootstrapper.cs:
public class UnityBootstrapper { public static IUnityContainer SetupUnity() { UnityContainer container = new UnityContainer(); container.RegisterType<IProductDbContext, ProductDbContext>() .RegisterType<IUnitOfWork, UnitofWork>(new InjectionConstructor(new ResolvedParameter(typeof(IProductDbContext)))) .RegisterType<IProductRepository, ProductRepository>() .RegisterType<IProductBusiness, ProductBusiness>(); } }
ProductController.cs:
public class ProductController : ControllerBase { private readonly IProductBusiness _productBusiness; public ProductController(IProductBusiness productBusiness) { _productBusiness = productBusiness; }
ProductBusiness.cs:
public class ProductBusiness : IProductBusiness, IDisposable { private readonly IUnitOfWork _unitOfWork; private readonly IProductRepository _productRepository; public ProductBusiness(IUnitOfWork unitOfWork) { _unitOfWork = unitOfWork; _productRepository = _unitOfWork.ProductRepository; } public override void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected override void Dispose(bool disposing) { if (!_isDisposed) { if (disposing) { if (_productRepository != null) _productRepository.Dispose(); if (_unitOfWork != null) _unitOfWork.Dispose(); } _isDisposed = true; } } ~ProductBusiness() { Dispose(false); } }
ProductRepository.cs:
public class ProductRepository : IProductRepository, IDisposable { private readonly IProductDbContext _context; public ProductRepository(IProductDbContext context) { if (context == null) throw new ArgumentNullException("context"); _context = context; } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (!_isDisposed) { if (disposing) { if (_context != null) _context.Dispose(); } _isDisposed = true; } } ~ProductRepository() { Dispose(false); } }
source share