简体   繁体   中英

Resolving dependencies with constructor injection and named mappings using attributes on the constructor parameter

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.

The attribute you are looking for is

[Dependency("A")]

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM