views:

93

answers:

1

I have the following httphandler:

public class NewHandler : IHttpHandler
{
    [Inject]
    public IFile FileReader
    {
        get;
        set;
    }

    public NewHandler()
    {
    }

    public void ProcessRequest(System.Web.HttpContext context)
    {
        ....
        var something = SomeMethod(FileReader);
        ....
    }

    public bool IsReusable
    {
        get
        {
            return true;
        }
    }
}

This is my Ninject Module in the Global.asax.

internal class ServiceModule : NinjectModule
{
    public override void Load()
    {
        Bind<IFile>().To<FileWrapper>().InSingletonScope();
    }
}

Every time the handler fires the FileReader is NULL. Am I missing something? Is this the correct way to do property injection using Ninject?

Thanks

+1  A: 

This is the correct way to do property injection with Ninject, but it won't work. You are probably using something like NinjectMvcApplication class as a base class for you application, that handles dependency injection for controllers and everything controllers might use (services, repositories). But HttpHandlers are not instantiated by the ControllerFactory so nothing takes care of injecting stuff.

Maybe there's better way to do it, but i used service locator to resolve the dependency. See http://code.dortikum.net/2010/08/05/asp-net-mvc-di-with-common-service-locator-and-ninject/.

UPDATE:

Try something like this:

public class NewHandler : IHttpHandler
{
    private readonly IFile _fileReader;

    public NewHandler()
    {
        _fileReader = ServiceLocator.Current.GetInstance<IFile>();
    }

    public void ProcessRequest(System.Web.HttpContext context)
    {
        ....
        var something = SomeMethod(_fileReader);
        ....
    }

    public bool IsReusable
    {
        get
        {
            return true;
        }
    }
}
Necros
Thanks! I read the article, interesting. Just to try it out I modified my application accordingly but I still manage to get NULL in the FileReader property when the ProcessRequest fires.
Thomas
@Thomas - see my update
Necros
Yes, that approach works. Still curious as to why httphandlers can't do property injections the same way a controller can. Probably something to do with the request pipeline. If anyone knows please let me know. Necros, thanks again!!
Thomas
As I explained in my answer, the controller factory takes care of injecting into controllers. If you wanted to inject into HttpHandlers automatically, you'd have to take control of what is creating HttpHandlers - http://msdn.microsoft.com/en-us/library/ms227439%28v=VS.100%29.aspx
Necros