Maxim V. Pavlov
Maxim V. Pavlov

Reputation: 10509

How to pass an HttpContext to a dependency initialization in MVC3 application

I am using Ninject in MVC3 application.

One of my resolvable dependencies makes use of HttpContext.Current.Server.MapPath("~/App_Data")

Back when I was initializing an IoC container in Global.asax (Application_Start), I was able to just define in my module configuration:

.WithConstructorArgument("basePath", HttpContext.Current.Server.MapPath("~/App_Data"));

Since my module was being initialized from the same thread as the Application, HttContext.Current wasn't null.

Then I had to move my Dependency Injection initialization to an PreAppStart method, using the WebActivator. Since the HttContext is not yet available in this scenario, I had to remove the parameter initialization of my dep.

I had worked around the problem by resoling the HttpContext inside my class instance at runtime. But it turns out it was possible only as long as the instance was being called from the Request Thread. As soon as I have moved the resolved instance call to a separate thread (not to be halting the Controllers' ActionResult generation), I arrived at the same problem - no longer able to get HttpContext. How can I resolve it in my scenario?

P.S. Just figured out I still can just call a method on my dependency from Global.asax Application start and feed the HttpContext from there. Nevertheless, let me know which is the best way to do it.

Upvotes: 4

Views: 1050

Answers (1)

Dmitry S.
Dmitry S.

Reputation: 8513

There should be a way in Ninject to register the dependency in a lazy way using a delegate. This way it will only resolve it when you access the dependency.

Here is how I do it using StructureMap:

For<HttpContextBase>().Use(c => new HttpContextWrapper(HttpContext.Current));

As far as accessing the HttpContext from a different thread, you can use the AsyncManager.Sync(d) method that takes a delegate and runs it in the ASP .NET worker process.

Upvotes: 1

Related Questions