hIpPy
hIpPy

Reputation: 5085

Unity named mapping issue

I have two implementations of IEmailService, one for testing and one for live (is-A). And I have a BusinessService that has-A IEmailService reference.

BusinessService
    IEmailService (has-A)

IEmailService
    TestEmailService (is-A)
    LiveEmailService (is-A)

In unity config, I register the two IEmailService implementations as follows.

<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
<container>
  <register type="DataAccess.IEmailService, DataAccess"
            mapTo="DataAccess.LiveEmailService, DataAccess"
            name="Live">
    <lifetime type="singleton" />
  </register>
  <register type="DataAccess.IEmailService, DataAccess"
            mapTo="DataAccess.TestEmailService, DataAccess"
            name="Test">
    <lifetime type="singleton" />
  </register>
<container>
</unity>

Based on the appSetting for IEmailService I want Unity to pick the correct implementation. This will help while testing.

<appSettings>
    <add key="IEmailService" value="Test"/>
</appSettings>

The issue is when unity resolves BusinessService, it tries to resolve (none) named mapping of IEmailService instead of Live or Test and throws an ResolutionFailedException.

container.Resolve<BusinessService>(); throws below exception:

BusinessServices.Test.BusinessServiceTest_Integration.Test103:

Microsoft.Practices.Unity.ResolutionFailedException : Resolution of the dependency failed, type = "BusinessServices.BusinessService", name = "(none)".
Exception occurred while: while resolving.
Exception is: InvalidOperationException - The current type, DataAccess.IEmailService, is an interface and cannot be constructed. Are you missing a type mapping?
-----------------------------------------------
At the time of the exception, the container was:

  Resolving BusinessServices.BusinessService,(none)
  Resolving parameter "emailService" of constructor BusinessServices.BusinessService(DataAccess.IEmailService emailService)
    Resolving DataAccess.IEmailService,(none)

  ----> System.InvalidOperationException : The current type, DataAccess.IEmailService, is an interface and cannot be constructed. Are you missing a type mapping?

The workaround I came up with is to specify the registrations in code as well and have a wrapper method around container.RegisterType to register IEmailService with (none) named mapping as well based on the appSetting value.

IUnityContainer container;

// registering unity
static void Load()
{
    container = new UnityContainer().LoadConfiguration();

    RegisterType<IEmailService, TestEmailService>("Test");
    RegisterType<IEmailService, LiveEmailService>("Live");
}

// register the `Test` or `Live` implementation with `(none)` named mapping as per appSetting
static void RegisterType<TFrom, TTo>(string name) 
    where TTo : TFrom
{
    var tFromAppSetting= ConfigurationManager.AppSettings[typeof(TFrom).Name];
    if (!string.IsNullOrEmpty(tFromAppSetting) && tFromAppSetting == name)
        container.RegisterType<TFrom, TTo>();
}

This works, but I end up specifying the registrations in two places - config as well as code. Is there a better way for doing this?

Update

I actually had got it correct by code. I do not need the unity config at all. The RegisterType<TFrom, TTo>(string name) registers either the Test or Live implementation as (none) named mapping depending on appSetting value. BusinessService is also resolved without exception.

As there is no unity config, I do not have load the configuration.

container = new UnityContainer();

Upvotes: 3

Views: 16388

Answers (1)

Rafal
Rafal

Reputation: 12619

In my opinion the only point of having registrations in config is to not have them in code and being able to replace implementation without recompilation. So you are write in trying to remove it form code. What I don't understand is why you want to have both registrations in config in the first place. Simply remove the Live one from config for tests and the Test from config for application and register them both without name.

So for instance in application app.config:

<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
   <container>
      <register type="DataAccess.IEmailService, DataAccess"
        mapTo="DataAccess.LiveEmailService, DataAccess">
              <lifetime type="singleton" />
     </register>

Since you really are determent to do it your way:

The other way around this is to register in code only a way of determining which instance is the default one:

 container.RegisterType<IEmailService>(new InjectionFactory((c)=>
   {
        var name = GetImplementationsNameFromAppSettings();
        return c.Resolve<IEmailService>(name);
   });

Upvotes: 5

Related Questions