Fallback instance for missing named type mapping

Aug 5, 2008 at 1:28 PM
Hi all,

I would like to configure my container in a way, that resolving a specific named type (e.g. a interface), a default instance is returned if no type mapping is registered for the specific name. As example, I have the following code fragment:

UnityContainer container = new UnityContainer();
container.RegisterType<ILogger, Logger>(new ContainerControlledLifetimeManager());

// Resolving without name will return a singleton
ILogger logger = container.Resolve<ILogger>();
// Resolving again without name will return the same instance
ILogger logger2 = container.Resolve<ILogger>();

// Resolving with a name will unfortunately fail but should also return the same "default" fallback instance
ILogger logger3 = container.Resolve<ILogService>("AnotherLogger");   

The above code shows the registration of a default logger. When resolving this logger without specific name, it works as expected. But as soon as resolving is done using a specific name, the resolving fails. Here I would like that the default instance is returned as if I would provide no name.

Is there a way to get this behavior. This way I could use the same logger for all my components and if there is some debugging to be done I could specify a specific logger just for that component.

Thanks for your help.
Aug 6, 2008 at 6:23 PM
Actually, if you try to resolve a concrete class with a name, it'll create a new instance by default.

This could be done, but it would require some extension work to configure the underlying ObjectBuilder policies properly. Let me think about it for a bit more.