Search code examples
unity-containerprism

Changing default lifetime manager of Unity container


Is there any way to make the ContainerControlledLifetimeManager the default lifetime manager for Unity container which is used with implicit registration e.g. through "registration by convention"? I basically want to have everything registered as Singleton unless explicitly registered differently.

Note: I use Unity in combination with Prism library so in case there is a solution with Prism that would be sufficient as well.


Solution

  • You can specify WithLifetime.ContainerControlled when using registration-by-convention, like

    containerRegistry.GetContainer().RegisterTypes( AllClasses.FromAssembliesInBasePath(),
                                                    WithMappings.FromMatchingInterface,
                                                    WithName.Default,
                                                    WithLifetime.ContainerControlled );
    

    You could also put your singletons into a folder Services and only register those with ContainerControlled.