UPDATE
Found this little stone that helped me with DbContext
Josh Kodroff - creating the Entity Framework with the ability to test units
Original
After a lot of research, I decided to implement IOC using Autofac in my MVC5 EF6 project. The Autofac documentation was useful, but I'm still not sure if I need to call Dispose () either in my controller or in the service class?
I do not use abstract UOW and the Generic Repository, but just rely on the DbContext and DbSet <> provided in EF6. Here is a snippet of my classes.
My dbcontext
public class ProductContext : DbContext
{
public ProductContext() : base("ProductContext")
{
}
public DbSet<Availability> Availability { get; set; }
public DbSet<Category> Categories { get; set; }
....
}
My class of service
public class ProductService : IProductService
{
private ProductContext _db;
public ProductService(ProductContext db)
{
_db = db;
}
public List<Product> GetProductsByCategory(string cleanCategory)
{
return _db.Products
.Include(p => p.Options.Select(o => o.OptionGroup))
.Include(p => p.Associations.Select(a => a.AssociatedGroup))
.Include(p => p.Variations).Include(p => p.Manufacturer)
.Where(p => p.Active && p.Category.Name.ToUpper().Equals(cleanCategory)).ToList();
}
.....
}
My service interface
public interface IProductService
{
List<Product> GetProductsByCategory(string cleanCategory);
....
}
My controller
public class ProductsController : Controller
{
private IProductService _productService;
public ProductsController(IProductService productService)
{
_productService = productService;
}
public ActionResult Index(string category)
{
if (String.IsNullOrEmpty(category))
{
return HttpNotFound();
}
string cleanCategory = urlScrubber(category);
var viewModel = new ProductsVM();
viewModel.ProductList = _productService.GetProductsByCategory(cleanCategory);
}
My Autofac Container
var builder = new ContainerBuilder();
builder.RegisterControllers(typeof(MvcApplication).Assembly);
builder.RegisterType<ProductContext>().AsSelf().InstancePerRequest();
builder.RegisterType<ProductService>().As<IProductService>().InstancePerRequest();
var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
Dispose() , Autofac , IDisposable. ProductContext DbContext, Dispose(), .
-
builder.RegisterType<ProductContext>().As<DbContext>().InstancePerRequest();
, , Dispose?
builder.RegisterType<ProductContext>().AsSelf().InstancePerRequest();
, Autofac UOW DbContext, .