I've been thinking of how I could use one instance of a DbContext
per HttpRequest
in a layered application. One of the solutions I came up with would be to create an HttpModule
that would initialize an instance of the context in HttpContext.Current.Items
in the BeginRequest
event handler and then dispose it in the EndRequest
event handler.
The approach above poses a problem though: I need to reference System.Web in my data layer and business layer in order to get a hold of the stored DbContext
instance. This is probably okay but I prefer to avoid going that route. What if I wanted to reference and use my data layer and business layers from a non-web application?
Any ideas?
You can use dependency injection. Simply create interface IContextHolder
with method to get a context and inject the instance into your lower layer from the web application. The implementation of this interface will be different for different types of applications - it will wrap the access to the real storage for your context instance.