Getting a reference to the container from the lifetime manager

Dec 19, 2010 at 8:24 PM

I know this might sound a bit odd, but within my lifetime container is there a way to get a reference to the container that is requesting the value?

The value I return will depend upon a system setting which I will read from a database.

Dec 20, 2010 at 1:28 AM

I assume you meant lifetime manager, not lifetime container? Lifetime containers aren't a plug-point in the container and is something rather different.

The lifetime manager interface is deliberately restricted, and there's no way to (currently) get the request context into the lifetime manager. You can probably do what you want a lot easier with a small custom strategy. Another option would be to grab the dependencies your lifetime manager needs at the time it's created and just store them away for later use. Otherwise, I'd need to see more details on what you're trying to do - I'm sure there's a way (or two, or seven) to do whatever you want.


Dec 20, 2010 at 10:23 AM
Edited Dec 20, 2010 at 10:44 AM

Hi Chris

Yes, lifetime manager.

I have created a kind of HierarchicalLifetimeManager which gets its value from a shared pool and returns to the pool when the child container is disposed.  What I need to do now is equivalent to database connection pooling.  My app always asks for the same interface (say IMyConnection) but because the implementing MyConnection uses a connection string from another service IMyConnectionSettings this means I cannot simply return just any MyConnection from my pool.

So what I am thinking of doing is something like this


container.RegisterType<IMyConnection, MyConnection>
  (new PooledLifetimeManager(
     container => 


So the PooledLifetimeManager has an action which it can execute to get the key to the relevant pool by passing in the container.

I was thinking of adding a Configure when the PooledLifetimeExtension is registered, but not sure if that is the right approach or not seeing as I've not done it before.  My code either uses the default pool, or uses alternate pools in a loop like so...


foreach(var dbInfo in DataConnectionInfos)
  using(var childContainer = container.CreateChildContainer())
    //Set the DB settings
    var settings = new MyConnectionSettings();
    settings.ConnectionString = dbInfo.ConnectionString;

    //Resolve the command handler and execute it
    var commandHandler = childContainer.Resolve<T>();


In this example the CommandHandler in question has a dependency to IMyConnection which is a pooled resource, but because this resource cannot have its ConnectionString altered once created I must retrieve a MyConnection from a specific pool keyed on ConnectionString.

I just threw lots of info at you there, I hope it was enough :-)