I have a large n-layered web project with self-tracking entities. I am using Entity Framework 5 and store the object context in HttpContext.Current.Items
and dispose it on Application_EndRequest
, as described here. I have a separate Class Library Project for the framework (CMS.Framework) which contains all the (self-tracking) POCO classes and much more logic. The actual ASP.NET Web Forms Applications refer to my CMS.Framework project. So far, it all works fine.
Now, I want to create a console application (for a scheduled server task) and also use my CMS.Framework class library. However, when a self-tracking entity tries to initalize (and calls the static CoreContext
property), a System.NullReferenceException
is thrown, as HttpContext.Current
is null. This makes sense to me, as we are in a console app right now. Here is my code that breaks only in the console app:
/// <summary>
/// Gets the CmsCoreContext in order to access the CMS_Core DB. This context
/// will be disposed when the application onloads (EndRequest).
/// </summary>
protected static CmsCoreContext CoreContext
{
get
{
if (!HttpContext.Current.Items.Contains("CoreContext"))
{
// Set Entity Framework context here and reuse it throughout the application
HttpContext.Current.Items.Add("CoreContext", new CmsCoreContext());
}
return HttpContext.Current.Items["CoreContext"] as CmsCoreContext;
}
}
Where shall I store the new CmsCoreContext()
when HttpContext.Current is null? Is there any console application context I can use? Any tips on this?