views:

511

answers:

3

Google/MyBrain are failing me. Without using a framework (which I'll never get past my colleagues), how do you inject a dependency into an HTTPModule given that you (the programmer) are not in control of creating the instance?

Are we into hacking up custom web.config sections + reflection or is there something cleaner I'm not seeing?

e.g. using Karl Seguin's example module as a base, and assuming the implementation of an ILogger. .Net 2.0 fwiw

public class ErrorModule : IHttpModule
{
    private ILogger injectedLogger; //how to set this?

    public void Init(HttpApplication application)
    {
     application.Error += (new EventHandler(this.application_Error));
    }

    public void Dispose() { /* required by IHttpModule */ }

    private void application_Error(object sender, EventArgs e)
    {
     this.injectedLogger.doStuff(e.ExceptionObject as Exception);
    }
}

It's things like this make me realise how much I despise MSDN.

A: 

You can use a very simple one-class ioc An IoC Container In 15 Minutes and 33 Lines

loraderon
Thanks for that - Make my own framework, eh? I have a working solution right now, but I'll review that link to see if it's a better one
annakata
+2  A: 

I've stumbled on a programatic solution. Eliminating web.config references entirely, you can add a module into global.asax if you're careful with the life-cycle.

In global.asax add:

public static ErrorModule myErrorModule;

public override void Init()
{
    base.Init();
    myErrorModule = new ErrorModule(new LogImplementer());
    myErrorModule.Init(this);
}

where "LogImplementer" implements ILogger, and just add a constructor to the httpmodule:

public ErrorModule(ILogger injected)
{
    this.Logger = injected;
}

There are some health warnings. You have to be really careful about where you do this int he global.asax (I'm pretty sure that Init() is right, but I'm not certain) and the module isn't added to the readonly HttpApplication.Modules collection. Other than that, works beautifully.

annakata
A: 

Please take a look at my answer here on similar question:

IoC Dependancy injection into Custom HTTP Module - how? (ASP.NET)