简体   繁体   中英

c# Console App with self-tracking entities: Where shall I store the EF5 DbContext instead in the HttpContext?

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?

Presumably you only want a single instance of your object context for the entire lifetime of your console application? Something like this should work:

private static CmsCoreContext _coreContext;

protected static CmsCoreContext CoreContext
{
   get
   {
      if (!System.Web.Hosting.HostingEnvironment.IsHosted)
      {
         return _coreContext ?? (_coreContext = new CmsCoreContext());
      }

      var context = HttpContext.Current;
      if (context == null) throw new InvalidOperationException();

      if (!context.Items.Contains("CoreContext"))
      {
         context.Items.Add("CoreContext", new CmsCoreContext());
      }

      return (CmsCoreContext)context.Items["CoreContext"];
   }
}

// The Application_EndRequest event won't fire in a console application.
public static void ConsoleCleanup()
{
   if (_coreContext != null)
   {
      _coreContext.Dispose();
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM