NInjecting into a asp.net website httphandler

六月ゝ 毕业季﹏ 提交于 2021-01-28 10:10:18

问题


I'm trying to inject a service into a HttpHandler i wrote. But all I'm getting is a Service with a null value.

I have created a small example to illustrate my problem using a normal asp.net website.

 public class MyHandler :IHttpHandler
{
    [Inject]
    public IHelloService HelloService { get; set; }

    public void ProcessRequest(HttpContext context)
    {
        context.Response.Write(HelloService.Hello());
    }

    public bool IsReusable { get; private set; }
}

The Service

 public interface IHelloService
{
    string Hello();
}

public class HelloService : IHelloService
{
    public string Hello()
    {
        return string.Format("Hello, the time is now {0}", DateTime.Now.ToShortTimeString());
    }
}

NinjectWebCommon.cs

private static void RegisterServices(IKernel kernel)
    {
        kernel.Bind<IHelloService>().To<HelloService>();
    }     

And finally my web.config

<httpHandlers>
   <add verb="*" path="*.aspx" type="HttpHandlerTest.App_Code.MyHandler" />
</httpHandlers>

I can see that there is a Ninject.Web.HttpHandlerBase, but when I use that, I simple get an empty response back and it never hits ProcessRequest.

Just for the record, this is what the MyHandler looks like when using HttpHandlerBase

 public class MyHandler :Ninject.Web.HttpHandlerBase
{
    [Inject]
    public IHelloService HelloService { get; set; }

    public void ProcessRequest(HttpContext context)
    {
        context.Response.Write(HelloService.Hello());
    }

    protected override void DoProcessRequest(HttpContext context)
    {

    }

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

回答1:


Found the solution to make it work. Modify the Myhandler.cs to this.

 public class MyHandler : Ninject.Web.HttpHandlerBase
{
    [Inject]
    public IHelloService HelloService { get; set; }

    protected override void DoProcessRequest(HttpContext context)
    {
        context.Response.Write(HelloService.Hello());
    }

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


来源:https://stackoverflow.com/questions/19964733/ninjecting-into-a-asp-net-website-httphandler

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!