tags:

views:

301

answers:

1

I am investigating the use of Autofac in our web application having previously used Castle Windsor in the past.

The thing that I really like with Autofac is being able to express dynamic component construction through lamda expressions, as opposed to creating DependancyResolvers etc. in Windsor.

One scenario I have is that I want a particular component to be registered at ASP.NET session level scope. With Windsor I would create/source a new LifestyleManager, however with Autofac I came up with this:

//Register SessionContext at HTTP Session Level
builder.Register(c =>
{
    HttpContext current = HttpContext.Current;

    //HttpContext handes delivering the correct session
    Pelagon.Violet.Core.Interfaces.SessionContext instance = current.Session["SessionContext"] as Pelagon.Violet.Core.Interfaces.SessionContext;

    if (instance == null)
    {
        instance = c.Resolve<Pelagon.Violet.Core.Interfaces.SessionContext>();
        current.Session["SessionContext"] = instance;
    }

    return instance;
})
.FactoryScoped();

Which at some point I might be able to turn into an extension method. I accept this implemtation will bomb if the HttpContext.Current.Session is null as it should only be used in a web app.

The question is:

What is the best practice for such a registration in Autofac. I have seen a lot of mention about the use of nested containers etc. but no concrete examples, and I am keen to understand what might be wrong with the above approach (only thing I can think of is the automatic disposal stuff).

Thanks.

A: 

This looks fine.

Marking the component 'ExternallyOwned()' will ensure that Autofac doesn't call Dispose() on it.

The only gotchas here are that your session-scoped component could resolve dependencies of its own via the current container, and thus hold references to things that may belong to the current request (for instance.) This should be easy to spot in testing though.

Cheers, Nick

Nicholas Blumhardt
Hi Nick. Thanks for the feedback, regarding using nested containers to manage scope within a web app, do you know of any concrete examples i.e. a Global.asx file thats would show where each container is built and "used"? Couldn't see it in the docs.
crowleym
Not sure it is 100% up-to-date, but this should help: http://code.google.com/p/autofac/source/browse/branches/1.4/src/Example/Remember.Web/Global.asax.cs
Nicholas Blumhardt