How to inject dependencies in an HttpModule using ninject?

We are launching a webforms project in my company, and I have the HttpModule that I need to resolve the dependencies.

We use the Ninject.Web library to resolve dependencies for main pages, pages, user controls, web services, and HttpHandlers. They all have base classes that you can inherit from the Ninject.Web namespace:

  • MasterPageBase
  • PageBase
  • WebServiceBase
  • HttpHandlerBase
  • And the custom one that we added since for some odd reason it wasn't there: UserControlBase

However, I cannot find the HttpModuleBase. There is a NinjectHttpModule, but it is not a base class, it is a real module that tries to eliminate the need to inherit base classes in pages and user controls, but it has some errors and we do not use it.

What is the best way to resolve my dependencies in my HttpModule?

When I talk about this with Google, I find this question on the first page -_-

+8
c # dependency-injection webforms ninject
source share
2 answers

I am a little surprised that no one answered this day all day! It looks like I surpassed you guys :)

Well, I solved the problem. I wrote my own implementation of IHttpModule and compiled it into the Ninject.Web assembly. Here is the source of the base class that I added:

 namespace Ninject.Web { public class HttpModuleBase : IHttpModule { /// <summary> /// This method is unused by the base class. /// </summary> public virtual void Dispose() { } /// <summary> /// Ininitialize the module and request injection. /// </summary> /// <param name="context"></param> public virtual void Init(HttpApplication context) { RequestActivation(); } /// <summary> /// Asks the kernel to inject this instance. /// </summary> protected virtual void RequestActivation() { KernelContainer.Inject(this); } } } 

I just modeled it after other base classes in the Ninject.Web assembly. It seems to work wonderfully. Just make your HttpModule an inheritance from Ninject.Web.HttpModuleBase , and then you can freely use property injection inside your module, for example:

 public class AppOfflineHttpModule : HttpModuleBase { [Inject] public IUtilitiesController utilitiesController { get; set; } ... } 
+2
source

Phil Haack blogged about a way to do this, which allows you to use constructor injection and thereby not make your HttpModule directly depend on Ninject. In the NinjectHttpApplication standard NinjectHttpApplication do the following:

Step 1

Use Nuget to find and add the HttpModuleMagic package to your web project.

Step 2

Write your HttpModule to use the constructor injection:

 public class MyHttpModule : IHttpModule { public MyHttpModule(ISomeService someService) {...} } 

Step 3

Remove the http module from your web.config:

 <httpModules> <!-- Modules will be defined via DI bindings --> </httpModules> 

Step 4

Set up bindings:

 Bind<IHttpModule>().To<MyHttpModule>(); // Repeat the pattern above for any other modules. 
+12
source

All Articles