I am working on a C# MVC5 project using EF6. Currently the context is created in the UnityConfig.cs class, which is called from the Application_Start() in Global. See some of use UnityConfig class below:
public static void RegisterComponents()
{
var container = new UnityContainer();
BlogSite.Domain.BlogSiteModelContainer context = new Domain.BlogSiteModelContainer();
container.RegisterType<IBlogRepository, BlogRepository>(new InjectionConstructor(context));
}
The problem with this is that the database may be updated directly and so the EF context will become inconsistent. So I need to change it so that it is re-loaded each time there is a new http request.
I have found that PerRequestLifetimeManager may be the solution for this, however, I can't find a good example of how I should use this.
How should I go about implementing this? Or is there a better way?
So I have tried a few things but still not getting anywhere. I realise I can add in a lifetime manager with the container.RegisterType()
method, but I assume that only applies to the repository and not the Entity Framework context.
e.g.
container.RegisterType<IBlogRepository, BlogRepository>(new PerRequestLifetimeManager(), new InjectionConstructor(context));
I'm still not sure how set the lifetime of the context. I realise I'll probably have to re-format the code a bit but I can't find an example of this situation anywhere.
I've been doing more research, and have looked at the idea of creating a Unit of Work to create the context within and pass it to the repositories. Not sure if its the best way forward, but it seems to be one that might work. Any thoughts on that?