this question Ninject Dependency Injection in MVC3 - Outside of a Controller is close to what I'm experiencing, but not quite.

I have an ASP.NET MVC3 site using Ninject 3 and it works wonderfully with constructor injection. All my dependencies are resolved, including those that pass in HttpContext.Current.

My issue is that in global.asax, I kick off a TaskManager class that periodically performs some tasks on a timer. Inside the TaskManager class, I don't have controllers, so if I need access to one of my dependencies (like my error logging service), I use a static wrapper class that has access to the kernel object:

var logger = MyContainer.Get<ILoggingService>();
logger.Error("error doing something...", ex);

The .Get method simply performs a kernel.Get call resolve my dependency. Works great every time I use this method on my other dependencies. However, ILoggingService has a dependency called MyWebHelper that is injected via it's constructor and includes HttpContext in it's constructor.

    public class DefaultLogger : ILoggingService
    {     
        public DefaultLogger(IRepository<Log> logRepository, IWebHelper webHelper)
        {
            _logRepository = logRepository;
            _webHelper = webHelper;
       }
    }

    public class MyWebHelper : IWebHelper
    {
      public MyWebHelper(HttpContext httpContext)
      {
          _httpContext = httpContext;
      }
    }

In the rest of my web site, this all works just fine because all the dependencies are injected into my MVC controllers. But what doesn't work is if I manually call my static wrapper class to get my dependencies that way. I get the error:

Error activating HttpContext using binding from HttpContext to method

Provider returned null.

So, it's not giving me an HttpContext like it does throughout the rest of my MVC application. I hope this makes sense, I'm not a ninject expert yet, but I'm trying...

有帮助吗?

解决方案

My issue is that in global.asax, I kick off a TaskManager class that periodically performs some tasks on a timer.

That's a bad idea as Phil Haack explains in details. Don't do this in your web application. Those recurring tasks should be done in a separate application (Windows Service or some console application which is scheduled to run at regular intervals).

Now the thing is that you are running background threads. Those background threads run outside of any user HTTP request and as a consequence HttpContext.Current is obviously null inside them. So even if you don't follow Phil Haack's advice and continue running background tasks in your ASP.NET application you will have to rearchitecture your method so that it no longer depends on any HttpContext because there's no such thing in those background threads.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top