Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

autofac - dependency injection into IHttpModule

New MVC 4 web application using autofac 3.0 on IIS 7.5. How do I inject a dependency into an IHttpModule?

I tried constructor injection which resulted in:

Constructor on type 'AnonymousIdentityModule' not found

So it seems the internals require a parameterless constructor for http modules. I also tried property injection too but that resulted in no dependency actually being injected.

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 see an equivalent in autofac.

like image 702
TugboatCaptain Avatar asked May 28 '13 23:05

TugboatCaptain


1 Answers

Check out this SO question: IoC Dependency injection into Custom HTTP 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 to HttpModules by creating another HttpModule to initialize them. And PH has provided a nuget package of his HttpModuleMagic if you want it:

PM> Install-Package HttpModuleMagic

But because HttpModules are only created once they are a kind of singleton, and your dependency also has to be a singleton (or rather, a single instance).

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

This looks at using a Factory function to retrieve a properly scoped dependency when needed.

like image 101
Simon C Avatar answered Nov 15 '22 08:11

Simon C