container icon indicating copy to clipboard operation
container copied to clipboard

Allow configuration of default lifetime manager

Open jimrogersiv opened this issue 7 years ago • 2 comments

In previous versions of Unity it was possible (if undocumented) to add an extension that would change the default lifetime manager for registrations that didn't specify one.

I've dug around in and debugged the 5.x code, and it doesn't seem to me that this is possible any longer. ILifetimePolicy is gone and I don't see a way to interrupt the resolve and specify a different one.

I think it should be possible to detect that the default transient instance is the one being used, and this would be an indicator that none was specified during registration. If there's a way to plug this into the strategy chain, I'm not seeing it.

Some links and discussion for the old way of doing this: https://stackoverflow.com/questions/29828410/default-the-lifetimemanager-to-the-singleton-manager-containercontrolledlifetim https://stackoverflow.com/questions/31420619/unity-change-default-lifetime-manager-for-implicit-registrations-and-or-disable

jimrogersiv avatar Apr 09 '19 19:04 jimrogersiv

I think this is an excellent idea. If you could provide summary on how it should work I could add the extension.

ENikS avatar Apr 10 '19 00:04 ENikS

What I'm thinking is: If you register with the extensions but don't specify a manager: container.RegisterType<IFoo, SomeFoo>(); OR if you don't explicitly register a class, but ask unity to resolve it, then we can tell unity which lifetime manager to use as the default.

In the first case of an explicit registration, unity will use TransientLifetimeManager.Instance when we don't specify one. We could infer from this that none was specified. But this is a bit of a hack because that's a public property. There's no reason I can't use it in a registration myself: container.RegisterType<IFoo, SomeFoo>(TransientLifetimeManager.Instance); In which case I would not want that manager replaced with some other default. I specified one!

The way the code is currently, I don't believe we can really determine which registration overload was called, so I don't think an extension can differentiate the two without changes to unity itself (for instance a property on the registration for lifetimeManagerSpecifiedAtRegistration or the like.)

For the second case of not registering a class at all: I think this is easily discoverable in the resolve phase (no registration in the collection) and an extension could be written to change the default manager using a policy. It's just not obvious to me exactly how to write that.

jimrogersiv avatar Apr 12 '19 17:04 jimrogersiv