Jeroen1984
Jeroen1984

Reputation: 1686

Ninject Scope per Owin Context

We have a very basic Owin application, where we want to use Ninject to resolve our dependencies. I would like to point out that there is no Web API or MVC or other middleware involved.

We set up a kernel like this:

private static StandardKernel CreateKernel()
    {
        var kernel = new StandardKernel();
        kernel.Bind<Test>().ToSelf().InRequestScope();
        kernel.Load(Assembly.GetExecutingAssembly());
        return kernel;
    }

The class Test is simplified for better explaination of the problem.

We tried to set up Ninject and register the Kernel as followoing:

 app.UseNinjectMiddleware(CreateKernel);

I really don't know if this is the way to go, but can't find anything similar in the documentation etc.

What we want is to resolve a single instance of Test, within the scope of the Owin request. So let's say we have the following middleware:

 app.Use((context,next) =>
            {
               // How to access my Ninject Kernel or our test instance here?
                return next.Invoke();
            });


 app.Use((context,next) =>
                {
                   // How to access the same Ninject Kernel or our Test instance here?
                    return next.Invoke();
                });

Does anybody know how to accomplish this???

Upvotes: 1

Views: 836

Answers (2)

Jeroen1984
Jeroen1984

Reputation: 1686

Ok so i figured it out...

Everything is working as expected when i add the Ninject.Web and Ninject.Web.Common NuGet packages to my project.

Now ik can use .InRequestScope(), and all my dependencies are created once (and shared) per request. Also all implementations of IDisposable are correctly disposed. It works just as it does when using WebAPI or MVC.

Upvotes: 0

ovolko
ovolko

Reputation: 2807

After looking into NInject code, it seems to me that NInject.Web.Common.OwinHost was not supposed to work without WebApi or, perhaps, some other add-on.

Indeed, InScope will work only if some component implements INinjectHttpApplicationPlugin, as follows from this code, and this interface is currently implemented only in specific extensions such as MVC, WebApi or WCF.

So I suggest the only way to go is to implement your own INinjectHttpApplicationPlugin. There are some ideas in this post and this answer might provide a building block for an easy scope discriminator for NInject.

Upvotes: 1

Related Questions