Ninject InRequestScope fallback to InThreadScope

2019-02-16 12:09发布

问题:

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 background runner that does some workflow management.

It fires up a new thread each 5 minutes and I Ninject my dependencies into this thread, If I change the scope to InThreadScipe the Dispose method is fired, but If i change it back to InRequestScope the Dispose method wont fire.

Is there a way of fallbacking to InThreadScope if InRequestScope isnt available?

Update: Just got an upvote for this question and why not update it with some additional info. I think that Ninjects way of handling life time is a bit outdated. Other IoC's have child containers were Transient registered objects live during the whole child container and are disposed when the child containers are. This is a much easier way of combining for example Web API with a custom worker like above scenario.

回答1:

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.



回答2:

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))


回答3:

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<INinjectHttpApplicationPlugin>().Select(c => c.RequestScope).FirstOrDefault(s => s != null);
    }

    public static IBindingWhenInNamedWithOrOnSyntax<T> InRequestFallbackScope<T>(this IBindingWhenInNamedWithOrOnSyntax<T> binding)
    {
        Func<IContext, object> 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<ICache>().Clear(Thread.CurrentThread); to trigger the (maybe existing) Dispose() on the objects you loaded in this scope (-> Thread.CurrentThread).



标签: scope ninject