开发者

ASP.NET - Create custom context object?

How do I create a global开发者_开发知识库ly accessible Context object similar to the HttpContext object?

I want to create a custom class library which I want to reference from a website project. In the website project I want to be able to call the following globally:

ClassLibraryName.Context

I cannot create a global property directly in my classlibrary, so how should this be implemented? (I've seen other applications/products use this approach, one of which is Sitecore which has a custom Sitecore.Context object available)

Edit

Might this be a 'valid' solution?

namespace MyLibrary
{
  public class Context
  {
    public static object ContextualObject
    {
      get;
      set;
    }
  }
}


Yes, this is not hard to implement, if you always run this class in the context of an ASP.NET application, use this approach:

namespace MyLibrary
{
  public class Context
  {
    public static object ContextualObject
    {
      get
      {
           var ctx = System.Web.HttpContext.Current.Items[typeof(Context)];
           if (ctx == null)
           {
               ctx = new Context();
               System.Web.HttpContext.Current.Items.Add(typeof(Context), ctx);
           }

           return ctx;
      }
      set { System.Web.HttpContext.Current.Items[typeof(Context)] = ctx; }
    }
  }
}

Essentially wrapping the existing HTTP context to provide your own service. This approach also doesn't store the object while the app lives, it only creates it for the current context, and when that response ends, it will die, and be regenerated during the next lifecycle. If that is not OK, store a static reference to context.

I've used this approach similarly in a class library I have at http://nucleo.codeplex.com, it works well.

HTH.


It depends on the lifetime you want the Context object to have. If you want all clients to use the same context, you can go with a singleton implementation.

If you want the context to be unique for each thread or http request you have to use a per request/thread implementation. One way to implement a per http request implementation would be to have a HttpModule create the object at every BeginRequest event and stick it in the HttpContext Items collection.

public static object ContextualObject 
{ 
  get { return HttpContext.Current.Items["MyContext"];} 
}


You could create an instance of the object on Session_Start in the Global.asax.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜