Reputation: 8266
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?
Upvotes: 0
Views: 1009
Reputation: 48230
One of the simplest solutions would be to wrap the access to the data context in a static property in a facade/gateway class.
This way, in a web application, the property could access the HttpContext.Current.Items
and store the context there. On the other hand, if the http context is missing, you could implement any other lifetime management policy for a non-web application.
public static TheDbContext Current {
get {
if ( HttpContext.Current != null ) {
// lifetime management for a web app
// e.g. with the Items container
}
else {
// lifetime management for a non-web app
}
}
}
The facade itself doesn't have to be a part of the data layer, you don't then reference System.Web
in a data layer.
Upvotes: 0
Reputation: 364249
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.
Upvotes: 1