Question

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.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top