Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autofac - Lifetime and modules

Tags:

oop

autofac

Problem (abstract)

Given a module which registers dependency X. The dependency X has a different lifetime in a MVC3 app (lifetime per HttpRequest) then in a console application (dependency per lifetimescope with a name). Where or how to specify the lifetime of dependency X?

Case

I've put all my database related code in a assembly with a module in it which registers all repositories. Now the ISession (Nhibernate) registration is also in the module.

ISession is dependency X (in the given problem case). ISession has different lifetime in a MVC3 app (lifetime per request) then in a console app where I define a named lifetimescope.

Should the registration of ISession be outside the module? Would be strange since it's an implementation detail.

What is the best case to do here? Design flaw or are there smart constructions for this :) ?

like image 337
mark_dj Avatar asked Jun 02 '12 18:06

mark_dj


People also ask

What is lifetime scope in Autofac?

Effectively, a lifetime scope equates with a unit of work in your application. A unit of work might begin a lifetime scope at the start, then services required for that unit of work get resolved from a lifetime scope. As you resolve services, Autofac tracks disposable ( IDisposable ) components that are resolved.

What is Autofac module?

A module is a small class that can be used to bundle up a set of related components behind a 'facade' to simplify configuration and deployment. The module exposes a deliberate, restricted set of configuration parameters that can vary independently of the components used to implement the module.

What is Autofac container?

Autofac is an addictive IoC container for . NET. It manages the dependencies between classes so that applications stay easy to change as they grow in size and complexity. This is achieved by treating regular . NET classes as components.


1 Answers

Given your use case description, I'd say you have a few of options.

First, you could just have each application register their own set of dependencies including lifetime scope. Having one or two "duplicate" pieces of code in this respect isn't that big of a deal considering the differences between the application and the fact that the registrations appear fairly small.

Second, you could wrap the common part (minus lifetime scope) into a ContainerBuilder extension method that could be used in each application. It would still mean each app has a little "duplicate code" but the common logic would be wrapped in a simple extension.

public static IRegistrationBuilder<TLimit, ScanningActivatorData, DynamicRegistrationStyle>
  RegisterConnection<TLimit, ScanningActivatorData, DynamicRegistrationStyle>(this ContainerBuilder builder)
{
  // Put the common logic here:
  builder.Register(...).AsImplementedInterfaces();
}

Consuming such an extension in each app would look like:

builder.RegisterConnection().InstancePerHttpRequest();
// or
builder.RegisterConnection().InstancePerLifetimeScope();

Finally, if you know it's either web or non-web, you could make a custom module that handles the switch:

public class ConnectionModule : Autofac.Module
{
  bool _isWeb;
  public ConnectionModule(bool isWeb)
  {
    this._isWeb = isWeb;
  }

  protected override void Load(ContainerBuilder builder)
  {
    var reg = builder.Register(...).AsImplementedInterfaces();
    if(this._isWeb)
    {
      reg.InstancePerHttpRequest();
    }
    else
    {
      reg.InstancePerLifetimeScope();
    }
  }
}

In each application, you could then register the module:

// Web application:
builder.RegisterModule(new ConnectionModule(true));

// Non-web application:
builder.RegisterModule(new ConnectionModule(false));

Alternatively, you mentioned your lifetime scope in your other apps has a name. You could make your module take the name:

public class ConnectionModule : Autofac.Module
{
  object _scopeTag;
  public ConnectionModule(object scopeTag)
  {
    this._scopeTag = scopeTag;
  }

  protected override void Load(ContainerBuilder builder)
  {
    var reg = builder.Register(...)
                     .AsImplementedInterfaces()
                     .InstancePerMatchingLifetimeScope(this._scopeTag);
  }
}

Consumption is similar:

// Web application (using the standard tag normally provided):
builder.RegisterModule(new ConnectionModule("httpRequest"));

// Non-web application (using your custom scope name):
builder.RegisterModule(new ConnectionModule("yourOtherScopeName"));

I would recommend against simply using InstancePerLifetimeScope in a web application unless that's actually what you intend. As noted in other answers/comments, InstancePerHttpRequest uses a specific named lifetime scope so that it's safe to create child lifetime scopes; using InstancePerLifetimeScope doesn't have such a restriction so you'll actually get one connection per child scope rather than one connection for the request. I, personally, don't assume that other developers won't make use of child lifetime scopes (which is a recommended practice), so in my applications I'm very specific. If you're in total control of your application and you can assure that you aren't creating additional child scopes or that you actually do want one connection per scope, then maybe InstancePerLifetimeScope will solve your problem.

like image 176
Travis Illig Avatar answered Dec 31 '22 18:12

Travis Illig