4

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?

3
  • Make it a parameter of the method that returns a configured container probably.
    – Casey
    Jul 29, 2014 at 23:33
  • To you really want to switch database while the application is running or is this runtimeChoice a value that fixed after startup (i.e. placed in the application's configuration file)?
    – Steven
    Jul 30, 2014 at 19:04
  • Nope it won't be changed while running, however it needs to be selected at runtime. The user has multiple sources available, so the code needs to cope with a selection at runtime.
    – Jason
    Jul 30, 2014 at 22:13

3 Answers 3

4

There are two things I would change, I would try to ensure those magic strings were handled as close to their source as possible and I would try to ensure my code was container agnostic.

I would have the following interface:

public interface IDataServiceFactory
{
    IDataService CreateSqlDataService();
    IDataService CreateOracleDataService();
}

With an implementation like so:

public class DataServiceFactory : IDataServiceFactory
{
    private readonly Func<IDataService> _sqlDataServiceFactory;
    private readonly Func<IDataService> _oracleDataServiceFactory;

    public DataServiceFactory(Func<IDataService> sqlDataServiceFactory, Func<IDataService> oracleDataServiceFactory)
    {
        _sqlDataServiceFactory = sqlDataServiceFactory;
        _oracleDataServiceFactory = oracleDataServiceFactory;
    }

    public IDataService CreateSqlDataService()
    {
        return _sqlDataServiceFactory();
    }


    public IDataService CreateOracleDataService()
    {
        return _oracleDataServiceFactory();
    }
}

I would then register this with your IUnityContainer like so:

_container.RegisterType<IDataService, DataService>("SQLDataService", 
    new InjectionConstructor(new ResolvedParameter<IDatabase>("SQLDatabase")));

_container.RegisterType<IDataService, DataService>("OracleDataService", 
    new InjectionConstructor(new ResolvedParameter<IDatabase>("OracleDatabase")));

_container.RegisterType<IDataServiceFactory, DataServiceFactory>(new InjectionConstructor(
    new ResolvedParameter<Func<IDataService>>("SQLDataService"), 
    new ResolvedParameter<Func<IDataService>>("OracleDataService"));

Now whatever was previously creating your Consumer instances should now have a dependency on IDataServiceFactory and should handle the runtime value to call the correct method CreateSqlDataService() or CreateOracleDataService().

All of your runtime code is now container agnostic and the magic strings are handled right next to their source.

1
  • Thanks. In this case there were no actual magic strings, I was just trying to demonstrate the situation that the user is making a selection at runtime, and that affects which object needed to be resolved as a dependency.
    – Jason
    Jul 30, 2014 at 22:21
2

I was able to resolve the correct type using a DependencyOverride, which itself obtained the required type from the unity container. So the consumer becomes:

public class Consumer
{
    IDataService dataService = null;
    public Consumer(string runtimeChoice)
    {
        DependencyOverride<IDatabase> dependency = null;

        if (runtimeChoice == "SQLSERVER")
        {
            dependency = new DependencyOverride<IDatabase>
                                 (Container.Resolve<IDatabase>("SQLDatabase"));

        }
        else if (runtimeChoice == "Oracle")
        {
            dependency = new DependencyOverride<IDatabase>
                                 (Container.Resolve<IDatabase>("OracleDatabase"));
        }            

        dataService = _container.Resolve<IDataService>(dependency);
    }
}
0

I have a similar requirement where I need to resolve a 'widgetbuilder' type at runtime. In my Unity Configuration I register my two types of widget builders:-

        container.RegisterType<IWidgetBuilder, SinglePointWidgetBuilder>("SinglePointWidgetBuilder");
        container.RegisterType<IWidgetBuilder, CurrentVsTargetWidgetBuilder>("CurrentVsTargetWidgetBuilder");

I then resolve them at runtime by:-

var container = UnityConfig.GetConfiguredContainer();
var widgetBuilder = container.Resolve<IWidgetBuilder>("SinglePointWidgetBuilder");

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.