Ninject InRequestScope fallback to InThreadScope

后端 未结 3 1680
抹茶落季
抹茶落季 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:08

    Thanks to Ruben I found a solution, however there sneaked in a little bug there in his pseudo code and since its a monday and Im tired I didnt see it right away :D

    StandardScopeCallbacks.Request
    

    Is a delegate and

    StandardScopeCallbacks.Request ?? StandardScopeCallbacks.Thread 
    

    will always return the left side since the delegate will never be null.

    There are two ways of doing this correctly,

    1 ExtensionMethod

    public static IBindingWhenInNamedWithOrOnSyntax InRequestFallbackScope(this IBindingWhenInNamedWithOrOnSyntax binding)
    {
        Func fallbackCallback = ctx => StandardScopeCallbacks.Request(ctx) ?? StandardScopeCallbacks.Thread(ctx);
        binding.Binding.ScopeCallback = fallbackCallback;
        return binding;
    }
    

    2 Using the InScope method

    .InScope(ctx => StandardScopeCallbacks.Request(ctx) ?? StandardScopeCallbacks.Thread(ctx))
    

提交回复
热议问题