9

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 :) ?

mark_dj
  • 984
  • 11
  • 29
  • Do you have specific lifetimes in mind for the connections? If so, are they different lifetimes per application or is it always the same regardless of application type? What about pooling? Do you pool in some apps but not others? – Travis Illig Jun 03 '12 at 07:06
  • It's like you said "The MVC extensions use a named scope to achieve the once-per-request mechanism.". The Http named scope isn't there when you use the module in console app. Currently I am looking at what the unit of work will be and that will be encapsulated in a scope. – mark_dj Jun 03 '12 at 07:59

2 Answers2

7

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.

Travis Illig
  • 23,195
  • 2
  • 62
  • 85
  • Thanks for the extensive answer! I have came up with this: https://gist.github.com/2883596 You call ConfigureUnitOfWork to configure on the dependency IUnitOfWork which hides the implementation details. Also this solution doesn't depend on the MVC3 extensions. Only downside to this solution is that you can configure everything while you only want to allow the lifetime,, could be abstracted away, but does cut if for now :) – mark_dj Jun 06 '12 at 18:02
0

It's common practice to use a one connection per http request. That being the case, connections would be registered using .InstansePerLifetimeScope(). For example, you might do something like:

builder
    .Register(c => {
                       var conn = new SqlConnection(GetConnectionString());
                       conn.Open();
                       return conn;
                   })
    .AsImplementedInterfaces()
    .InstancePerLifetimeScope();
Jim Bolla
  • 8,265
  • 36
  • 54
  • Yes I know you can do that. My problem is where to do this? It is something the 'data' module should be responsible for. However there seems to be no way to register the connection inside the module and set the lifetime outside the module. – mark_dj Jun 02 '12 at 19:58
  • I would register the connection and set the lifetime inside the data module. – Jim Bolla Jun 02 '12 at 21:15
  • Thats the problem in a MVC app the lifetime is different as in a console app where there is no such thing as a context like Http – mark_dj Jun 02 '12 at 21:22
  • InstancePerLifetimeScope() is agnostic. In a console app, there will probably be just the one lifetimescope. In an asp.net app, autofac will tie the lifetimescope to the httpcontext for you. It's quite clever actually. – Jim Bolla Jun 02 '12 at 22:16
  • 1
    Simply InstancePerLifetimeScope won't guarantee just one per HTTP request. If you create any nested lifetime scopes during a single request, you'll get one for every nested scope, too. The MVC extensions use a named scope to achieve the once-per-request mechanism. – Travis Illig Jun 03 '12 at 06:55
  • That's true, but I'd say it's uncommon to spawn nested scopes inside and even if you were, you may want, or at least be ok with, a second db connection for the nested scopes. – Jim Bolla Jun 03 '12 at 18:26