Autofac - dependency injection in IHttpModule

New MVC 4 web application using autofac 3.0 on IIS 7.5. How to add dependency in IHttpModule?

I tried using the constructor, which resulted in:

Constructor of type AnonymousIdentityModule not found

Thus, it seems that the internal elements need a parameterless constructor for the http modules. I also tried to inject properties, but this did not lead to the actual injection of the dependency.

registration

builder.RegisterType<AnonymousIdentityModule>().As<IHttpModule>().PropertiesAutowired().InstancePerHttpRequest(); 

IHttpModule Code

 public class AnonymousIdentityModule : IHttpModule { private readonly IServiceManager _serviceManager; // this causes "constructor not found" exception public AnonymousIdentityModule(IServiceManager serviceManager) { _serviceManager = serviceManager; } // never assigned by autofac public IServiceManager ServiceManager { get { return _serviceManager; } set { _serviceManager = value; } } ... } 

web.config

  <system.webServer> <validation validateIntegratedModeConfiguration="false" /> <modules> <add name="AnonymousIdentityModule" type="AnonymousIdentityModule" /> </modules> </system.webServer> 

I found this old article related to Windsor, but did not find an analogue in the autofac.

+5
source share
1 answer

Check out this SO question: Embedding IoC dependencies in an HTTP user module - how? (ASP.NET)

and this post by Phil Haack: http://haacked.com/archive/2011/06/02/dependency-injection-with-asp-net-httpmodules.aspx

They both talk about providing DI for HttpModules by creating another HttpModule to initialize them. And PH provided the nuget package of its HttpModuleMagic if you want:

 PM> Install-Package HttpModuleMagic 

But since HttpModules modules are created only when they are kind of singleton, and your dependency should also be singleton (or rather, a single instance).

So, if you need a dependency for each request, check out this post: http://blog.sapiensworks.com/post/2013/03/18/Http-Module-Dependecy-Injection-with-Autofac-Gotcha.aspx

This section discusses the use of the Factory function to obtain the correct scope if necessary.

+7
source

Source: https://habr.com/ru/post/1483248/


All Articles