Using Ninjects InRequestScope() when selfhosting Web API

.net, asp.net-mvc-3, asp.net-web-api, c#, ninject

Solution

You can use the NamedScope extensions to define that the controller defines a scope and use that scope for everything that is in a request scope. Best you use conventions for this definition:

const string ControllerScope = "ControllerScope"; 
kernel.Bind(x => x.FromThisAssembly()
                  .SelectAllClasses().InheritedFrom<ApiController>()
                  .BindToSelf()
                  .Configure(b => b.DefinesNamedScope(ControllerScope)));

kernel.Bind<IMyComponent>().To<MyComponent>().InNamedScope(ControllerScope);

I recommend to implement `INotifyWhenDisposed` for the controllers so that the objects in request scope are immediately released after the request. E.g. by deriving from the following class instead of `ApiController`

public abstract class NinjectApiController : ApiController, INotifyWhenDisposed
{
    protected override void Dispose(bool disposing)
    {
        base.Dispose(disposing);
        this.IsDisposed = true;
        this.Disposed(this, EventArgs.Empty);
    }

    public bool IsDisposed
    {
        get;
        private set;
    }

    public event EventHandler Disposed;
}

I try to provide an extension for WebAPI selfhosting somewhen in the comming weeks.

EDIT:

Selfhosting support is now provided by Ninject.Web.WebApi.Selfhosting https://nuget.org/packages/Ninject.Web.WebApi.Selfhost/3.0.2-unstable-0

Example: https://github.com/ninject/Ninject.Web.WebApi/tree/master/src/Ninject.Web.WebApi.Selfhost

Problem

I'm creating an application that has a ASP.NET Web API interface using the Self Hosting approach. I want to use a scope similar to `InRequestScope()` provided by MVC3. When I host a Web API application on the IIS this seems to be supported by Ninject.Extension.WebAPI. But when self hosting the WebAPI I get a new instance when I create bindings `InRequestScope()`. Is there any way I can use this scope when I self host the web API?

Original source