Concrete Types + Lifetime Manager

Apr 4, 2008 at 3:00 PM
One of the pros of Unity is that it can try to create any type without prior registration:

UnityContainer container = new UnityContainer();
Foo foo = container.Resolve<Foo>();

However, we lose the capability to control life time as we could do with registration:

UnityContainer container = new UnityContainer()
  .RegisterType<Foo>(new ContainerControlledLifetimeManager()); // Singleton
 
Foo foo = container.Resolve<Foo>();

Could it make sense to have a Resolve overload that takes a lifetime manager? In a prior implementation, I had something like:

UnityContainer container = new UnityContainer();
Foo foo = container.Resolve<Foo>(PerSessionLifetime.Instance); //Similar to a Find or Create
Apr 4, 2008 at 5:11 PM
Would that essentially be adding write privileges to what is semantically thought of as a read operation?

I can see the value, but am not sure if this would result in something negative by coupling register and resolve.

Regards,

Dave
Apr 4, 2008 at 6:22 PM
Here's the problem with this suggestion. What happens if I do this?

container.Resolve<Foo>(new ContainerControlledLifetimeManager());
container.Resolve<Foo>(new PerThreadLifetimeManager());
container.Resolve<Foo>(new PerSessionLifetimeManager());

If you want to control lifetime, you've just got to register.