Skip to content

Instantly share code, notes, and snippets.

@kkozmic
Created March 8, 2011 08:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kkozmic/860021 to your computer and use it in GitHub Desktop.
Save kkozmic/860021 to your computer and use it in GitHub Desktop.
public class TransientScopedInWebRequestLifestyleModule : IHttpModule
{
// Fields
private const string key = "trolls_and_goblins";
public static IKernel kernel;
// Methods
public void Dispose()
{
}
public void Init(HttpApplication context)
{
context.EndRequest += Application_EndRequest;
}
public static void Init(IKernel kernel)
{
TransientScopedInWebRequestLifestyleModule.kernel = kernel;
}
protected void Application_EndRequest(object sender, EventArgs e)
{
var application = (HttpApplication) sender;
var candidates = (IEnumerable<object>) application.Context.Items[key];
if (candidates != null)
{
application.Context.Items.Remove(key);
foreach (object instance in candidates.Reverse())
{
kernel.ReleaseComponent(instance);
}
}
}
public static void RegisterForEviction(object instance)
{
HttpContext context = HttpContext.Current;
var list = (List<object>) context.Items[key];
if (list == null)
{
list = new List<object>();
context.Items[key] = list;
}
list.Add(instance);
}
public static void Evict(object instance)
{
HttpContext context = HttpContext.Current;
var list = (List<object>) context.Items[key];
if (list != null)
{
list.Remove(instance);
}
}
}
public class TransientScopedInWebRequestLifestyleManager : AbstractLifestyleManager
{
public override object Resolve(CreationContext context)
{
object instance = base.Resolve(context);
TransientScopedInWebRequestLifestyleModule.RegisterForEviction(instance);
return instance;
}
public override bool Release(object instance)
{
TransientScopedInWebRequestLifestyleModule.Evict(instance);
return base.Release(instance);
}
public override void Dispose()
{
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment