Reputation: 325
I think I'm facing an architecture problem I can solve:
I'm developing a web applicationusing entity framework code first (v4.3 beta1). Also, there are a few web services published.
In a separate Class Library, I have the DbContext and al, the entities. This library is referenced by the web application, obviuously.
In the "Data" library, I have a static property to hold de context:
namespace MMOrpheus.Lib
{
public class Context
{
public static MMOrpheusDB MMO
{
get
{
if (HttpContext.Current != null && HttpContext.Current.Session["MMOEntities"] == null)
{
HttpContext.Current.Session["MMOEntities"] = new MMOrpheusDB();
}
return HttpContext.Current.Session["MMOEntities"] as MMOrpheusDB;
}
set
{
if (HttpContext.Current != null)
HttpContext.Current.Session["MMOEntities"] = value;
}
}
}
}
MMOrpheusDB inherit from DbContext.
So the problem is I someway feel this is not right. Among other things, I don't think this Context class should be using System.Web!
Any suggestions on how to organize this project?
Upvotes: 2
Views: 2118
Reputation: 8198
The answer to your question is not a simple one.
First of all I suggest, you use a dependency injection & inversion of control framework (StructureMap,Unity,...).
If you are going to store your DbContext, using an IOC will make it so easy. You can define lifetime of your context. I normally go with PerRequest life time. One instance of DbContext for each web request. DBContext starts with a request and ends with it.
But there is no need to go with this pattern. You can simply start you context when you need it and dispose it after using it.
If you prefer the first approach, search for Domain Driven Design, IOC, Unit Of Work, Repository Pattern & etc.
Upvotes: 3