In my MVC3 project I\'ve setup my kernel to Ninject the Entityframework context on a InRequestScope basis, this works perfect. But I have a ba
This is what I composed to have the request scope in the first place and the thread as a fallback.
public static class NinjectBindingExtensions
{
private static bool IsRequestPresent()
{
try
{
return HttpContext.Current != null;
}
catch
{
return false;
}
}
private static object GetScope(IContext ctx)
{
// note: this is a copy of the private method of Ninject.Web.Common.RequestScopeExtensionMethod#GetScope
return ctx.Kernel.Components.GetAll().Select(c => c.RequestScope).FirstOrDefault(s => s != null);
}
public static IBindingWhenInNamedWithOrOnSyntax InRequestFallbackScope(this IBindingWhenInNamedWithOrOnSyntax binding)
{
Func fallbackCallback = ctx => IsRequestPresent() ? GetScope(ctx) : StandardScopeCallbacks.Thread(ctx);
binding.BindingConfiguration.ScopeCallback = fallbackCallback;
return binding;
}
}
If you are in the Thread scenario make sure you call _kernel.Components.Get to trigger the (maybe existing) Dispose() on the objects you loaded in this scope (-> Thread.CurrentThread).