| « Bonjour Updated | Parameterized Modal Popup » |
Reusable singleton in ASP.NET Context
Hi everyone,
After reading Ayende Rahien's post, I told my self that I had to share my Http Singleton module I am using for some time now. This module enables me with a few lines of code to have a single instance of what ever I could want. If like Ayende, you are using NHibernate, you just would need to inherit from the code I'll give you to make your own HttpSessionModule, and thus have one session created by httpcontext. I use it to have not only an ObjectContext (I am using euss), but a service which hides this persistence layer.
Here is my abstract Http Singleton module implementation :
public abstract class HttpSingletonModule<T> : IHttpModule
{
#region IHttpModule Members
public void Dispose()
{
}
public void Init(HttpApplication application)
{
application.PostAuthorizeRequest +=
new EventHandler(application_AuthorizeRequest);
application.EndRequest +=
new EventHandler(application_EndRequest);
}
void application_EndRequest(object sender, EventArgs e)
{
HttpApplication application = sender as HttpApplication;
HttpContext context = application.Context;
if (context != null)
{
T instance =
(T)context.Items[typeof(T).AssemblyQualifiedName];
if (instance is IDisposable)
((IDisposable)instance).Dispose();
}
}
public static T Instance
{
get
{
return (T)HttpContext.Current.Items[typeof(T).AssemblyQualifiedName];
}
set
{
HttpContext.Current.Items[typeof(T).AssemblyQualifiedName] = value;
}
}
void application_AuthorizeRequest(object sender, EventArgs e)
{
HttpApplication application = sender as HttpApplication;
HttpContext context = application.Context;
if (context != null)
context.Items.Add(typeof(T).AssemblyQualifiedName,
CreateInstance(context));
}
protected abstract T CreateInstance(HttpContext context);
#endregion
}
As you may have understood now, To implement your module, it is quite easy. Here is the implementation I am using in a projet :
public class PortalServiceModule : HttpSingletonModule<PortalService>
{
protected override PortalService CreateInstance(HttpContext context)
{
if (context.User.Identity.IsAuthenticated)
return new PortalService(context.User.Identity.Name);
return new PortalService();
}
}
You see ? so few lines of code for such a simplicity of use : to get my portal service instance, I just have to call the static Instance property of my PortalServiceModule. How could it be simpler ?
1 comment
Comments are closed for this post.