3

I have the following Service class constructor:

public class Service : IService
{
    private readonly IRepository _repository;

    public Service(IRepository repository)
    {
        _repository = repository;
    }

    // ...
}

IRepository has two named implementations. I want to Resolve IService but need to set which IRepository implementation should be used (Service should be flexible and I can't put Dependency attribute to IRepository constructor parameter).

Is there any way to implement it by Unity?

1 Answer 1

3

You can use the unity config section to achieve this. Check this link.

In the config section you can specify the mapping as follows.

 <type type="IMyService" mapTo="MyDataService" name="DataService">
      <typeConfig extensionType="Microsoft.Practices.Unity.Configuration.TypeInjectionElement,
                                 Microsoft.Practices.Unity.Configuration">
        <constructor>
          <param name="connectionString" parameterType="string">
            <value value="AdventureWorks"/>
          </param>
          <param name="logger" parameterType="ILogger">
            <dependency />
          </param>
        </constructor> 
        <property name="Logger" propertyType="ILogger" />
        <method name="Initialize">
          <param name="connectionString" parameterType="string">
            <value value="contoso"/>
          </param>
          <param name="dataService" parameterType="IMyService">
            <dependency />
          </param>
        </method>
      </typeConfig>
    </type>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.