Ninject InRequestScope fallback to InThreadScope

后端 未结 3 1682
抹茶落季
抹茶落季 2021-01-11 14:28

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

3条回答
  •  一个人的身影
    2021-01-11 15:24

    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().Clear(Thread.CurrentThread); to trigger the (maybe existing) Dispose() on the objects you loaded in this scope (-> Thread.CurrentThread).

提交回复
热议问题