问题
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