I have a scenario using Unity which is a bit confusing… Say I have an AuthenticationService that authenticates users and when successful logs to a text file or database using TextLogger class or DbLogger class respectively. Normally for which ever class I will use in my project I would register appropriately in my module class as below:
public class LoggingModule
{
IUnityContainer _iocContainer;
public LoggingModule(IUnityContainer container)
{
_iocContainer = container;
}
public void Init()
{
//Add any logic here to look in a config file, check a property
//or any other condition to decide which implementation is registered.
//register the database logger to the ILogger interface
_iocContainer.RegisterType(typeof(ILogger), typeof(DBLogger));
}
}
And this will be injected into the constructor of my Authentication Service. However if I wanted to use both loggers at different points in my application, first do I Register both types in my Init method, i.e. the TextLogger and DBLogger?
Second, how does my container know which type to Resolve?
Please help….
Register your both types into container with a name, i.e.;
and resolve your types using the name parameter, i.e.;