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 :) ?
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.
Consuming such an extension in each app would look like:
Finally, if you know it's either web or non-web, you could make a custom module that handles the switch:
In each application, you could then register the module:
Alternatively, you mentioned your lifetime scope in your other apps has a name. You could make your module take the name:
Consumption is similar:
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; usingInstancePerLifetimeScope
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 maybeInstancePerLifetimeScope
will solve your problem.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: