Ninject InRequestScope fallback to InThreadScope

There's an InScope method, with which you can specify a custom scoping rule.

The implementation of InRequestScope is currently undergoing change from 2.2-2.4.

So go to the source of your version, look at the impl of InRequestScope and InThreadScope and create an amalgam (which you can then slot in as an extension method alongside the other InXXXScope methods.

It'll look (before you extract it into an extension method) something like:

Bind<X>.To<T>().InScope( ctx => ScopeContext.Request(ctx) ?? ScopeContext.Thread(ctx))

The other way is to create two Bindings, with an appropriate constraint such as WhenInjectedInto<T> to customize the scoping based on the contextual binding.


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<T> InRequestFallbackScope<T>(this IBindingWhenInNamedWithOrOnSyntax<T> binding)
{
    Func<IContext, object> 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))

Tags:

Scope

Ninject