I am using Unity for dependency injection and I want to control at runtime, which particular type is resolved and passed into a constructor as a dependency.
I have an interface:
public interface IDatabase
{
void DoSomething();
}
That is implemented by two classes:
public class SQLDatabase : IDatabase
{
public void DoSomething()
{
//Do Something on a SQL server database...
}
}
public class OracleDatabase : IDatabase
{
public void DoSomething()
{
//Do Something on an Oracle database...
}
}
A third class has a dependency on IDatabase
public class DataService: IDataService
{
public DataService(IDatabase database)
{
database.DoSomething();
}
}
The module registers each class with Unity and the two IDatabase types are given specific names so that they can be differentiated:
container.RegisterType<IDatabase, SQLDatabase>("SQLDatabase");
container.RegisterType<IDatabase, OracleDatabase>("OracleDatabase");
container.RegisterType<IDataService, DataService>();
I need to create an instance of a Consumer, at which point I want to specify which of the two types that implement IDatabase are to be used/injected by Unity, but I don't know how to tell Unity which specific type to construct/resolve? I guess I want something like this (Pseudo code):
public class Consumer
{
IDataService dataService = null;
public Consumer(string runtimeChoice)
{
if (runtimeChoice == "SQLSERVER")
{
dataService = _container.Resolve<IDataService>("SQLDatabase");
}
else if (runtimeChoice == "Oracle")
{
dataService = _container.Resolve<IDataService>("OracleDatabase");
}
}
}
So, how do I tell Unity to resolve the IDatabase type, using the specific named type, and pass it into the constructor of dependent objects, but doing it at runtime?
runtimeChoicea value that fixed after startup (i.e. placed in the application's configuration file)?