Most people understand how to use the Unity framework, or at least I hope.  Microsoft Unity is a pretty useful DI container.  If you need to learn more about it, check out my article on dotnetslackers here: http://dotnetslackers.com/articles/aspnet/Using-Microsoft-Unity-in-ASP-NET-MVC.aspx.  In this example, there is a sample custom configuration file that registers unity contract types to their mapped implementation types.  Take a look at the configuration snippet below.

 

<unity
  <typeAliases
    <typeAlias alias="CommonInt" type="Nucleo.Context.IService, Nucleo" /> 
  </typeAliases
  <containers
    <container name="Repositories"
      <types
        <type type"App.ICustomerRepository, App.Business" mapTo="App.CustomerRepository, App.Business" />      
        <type type"App.IProductRepository, App.Business" mapTo="App.ProductRepository, App.Business">
          <constructor />
        </type>
      </types
    </container>
  </containers
</unity>
Here is where the challenge comes in.  If, for some reason, say the mapped type App.CustomerRepository was mapped incorrectly, or may not implement App.ICustomerRepository, Unity gives you this vague message about the error with no actual details to the problem.  This problem has been common to many developers that you see it plastered on forums or blogs across the web.  I’m posting this because I resolved the issue, but it requires some additional work.
To start, we need to directly access the unity configuration section by loading up the config section as so:
UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection(“unity”);
Rather than letting unity register the types, which it has a method to do this for you, I register the types directly by doing something like the following:
foreach (var typeEntry in section.Containers[“Repositories”].Registrations) //Repositories specified in config
{
   Type fromType, toType;

    try
    {
       fromType = Type.GetType(typeEntry.TypeName);
    }
    catch
    {
       throw new Exception(“Could not create the contract type: ” + typeEntry.TypeName);
    }

    try
    {
      toType = Type.GetType(typeEntry.MapToName);
    }
    catch
    {
        throw new Exception(“Could not create the mapped type: ” + typeEntry.MapToName);
    }

    try
    { 
       container.RegisterType(fromType, toType);
    }
    catch
    {
        throw new Exception(“Could not register the mappings: ” + typeEntry.TypeName + ” to ” + typeEntry.MapToName);
    } 

A little extra work, but this exception handling scheme points directly to the root cause of the problem.  It really saved me a lot of time.  Additionally, this works really well if you make it an extension method, or a static utility method.