CountZero
CountZero

Reputation: 6389

IHttphandler Property Injection In MVC2 Using Ninject

I'm looking for a way to do property injection in MVC for IHttpHandlers.

In the case of webforms ninject you could just inherit from HttpHandlerBase.

This no longer works as the application now inherits from Ninject.Web.Mvc.NinjectApplication NOT Ninject.Web.NinjectHttpApplication.

This application registers types for controllers not PageBase, MasterPageBase or HttpHandlerBase.

Rubbish.

Is their a way of doing it maybe with the MvcHandler class?

The post below is the closest I've come to an answer.

HttpHandler Property Injection using Ninject returning null

Upvotes: 2

Views: 662

Answers (1)

Lachlan Roche
Lachlan Roche

Reputation: 25946

If you build Ninject.Web.Mvc from source, include a copy of the HttpHandlerBase class from Ninject.Web in the Ninject.Web.Mvc namespace.

Otherwise your own HttpHandlerBase will need to call Kernel.Inject on itself. The kernel reference can be obtained via Application scope, or via reflection.

In HttpApplication.CreateKernel() store the kernel instance in the Application scope as "NinjectKernel". Then add the following as your IHttpHandler base class.

public abstract class HttpHandlerBase : IHttpHandler
{
    public abstract void ProcessRequest( HttpContext context );

    void IHttpHandler.ProcessRequest( HttpContext context )
    {
        var kernel = (IKernel) context.Application["NinjectKernel"];
        kernel.Inject( this );

        this.ProcessRequest( context );
    }
}

The reflection approach does not require any code in your HttpApplication.

public abstract class HttpHandlerBase : IHttpHandler
{
    public abstract void ProcessRequest( HttpContext context );

    void IHttpHandler.ProcessRequest( HttpContext context )
    {
        Assembly ass = Assembly.Load("Ninject.Web.Mvc");
        Type type = ass.GetType("Ninject.Web.Mvc.KernelContainer");
        MethodInfo init = type.GetMethod("Inject", BindingFlags.Static | BindingFlags.Public, null, new Type[] { typeof(object) }, null );
        init.Invoke( null, new object[] {} );

        this.ProcessRequest( context );
    }
}

Upvotes: 2

Related Questions