0

Let's suppose I have two different concrete classes that both implement the same interface:

public interface IDataSource{
    Connection CreateConnection();
}

public class DataSourceA: IDataSource
{
    ....
}

public class DataSourceB: IDataSource
{
    ....
}

Now I want to register both of these with my unity container:

var container = new UnityContainer();
container.RegisterType<IDataSource, DataSourceA>("A");
container.RegisterType<IDataSource, DataSourceB>("B");

I know that I can specify the mapping name when I resolve a dependency :

var myDataSource = conatiner.Resolve<IDataSource>("A");

However, in my case, I won't be resolving the dependency myself. I am creating many different controllers and I will be using UnityDependencyResolver (from ASP.Net MCVC) to create all the controllers. Some of my controllers required DataSource A, some require DataSource B, and some require both. What I'd like to do is specify which one to use as an attribute on the constructor parameter, like this:

public class ReportController{
  public ReportController([InjectionQualifier("A")] IDataSource dataSource)
  {
    ...
  }
}

Is something like that possible? I come from the spring world in java and I would use an @Qualifier annotation in this case using that stack.

Kyle
  • 3,775
  • 6
  • 37
  • 47
  • 1
    What you want is exactly possible. See here http://stackoverflow.com/questions/7046779/with-unity-how-do-i-inject-a-named-dependency-into-a-constructor – SouthShoreAK Dec 11 '13 at 22:49

2 Answers2

1

The attribute you are looking for is

[Dependency("A")]

With Unity how do I inject a named dependency into a constructor?

Community
  • 1
  • 1
SouthShoreAK
  • 4,176
  • 2
  • 26
  • 48
  • Thanks. I tried that a while back but the only 'Dependency' attribute was in the System.Runtime.CompilerServices namespace. Now I see that my problem was that my project did not have a dependency on the unity assembly. – Kyle Dec 11 '13 at 23:00
0

I personally don't like using the Dependency Attribute because you're directly depending on the Unity library. You might as well pass in the IUnityContainer in your constructor.

Usually when you need to use named dependencies, it's because you are trying to implement some kind of strategy pattern.

What I do is that I isolate Unity in a class called StrategyResolver and inject the StrategyResolver as dependency. Since the StrategyResolver belongs to me then my "services" classes no longer have any hard dependencies on any Unity library objects except inside the StrategyResolver but that's acceptable since I will never have to modify the StrategyResolver ever again when adding new strategies in the future.

Take a look, I've detailed my approach in this answer with code examples : https://stackoverflow.com/a/37882179/483638

Community
  • 1
  • 1
TchiYuan
  • 4,258
  • 5
  • 28
  • 35