2012-08-29

Unity.BuildUp–Ambiguous constructor

Sometimes you have no control over the instantiation of your classes and therefore cannot use Unity. For this reason the BuildUp method was added to Unity in order to either call the method marked with [InjectionMethod] or to set all properties marked with [Dependency].  Unfortunately in the latest build this is broken.  For some reason BuildUp searches for a suitable constructor even though the instance has already been created.  In my case I have two constructors both with only 1 parameter so I get an ambiguous constructor exception.

So, I created this helper method to call the InjectionMethod on the instance…

public static class UnityContainerHelper
{
public static void CallInjectionMethod(this IUnityContainer unityContainer, object instance, params ResolverOverride[] overrides)
{
if (instance == null)
throw new ArgumentNullException("Instance");

var injectionMethodInfo
= instance.GetType().GetMethods().Where(x => x.GetCustomAttributes(typeof(InjectionMethodAttribute), true).Any()).SingleOrDefault();
if (injectionMethodInfo == null)
return;
var parameters
= injectionMethodInfo.GetParameters();
if (parameters.Length == 0)
return;

var dependencies
= new object[parameters.Length];
int index = 0;
foreach (Type parameterType in parameters.Select(x => x.ParameterType))
{
dependencies[index]
= unityContainer.Resolve(parameterType, overrides);
index
++;
}
injectionMethodInfo.Invoke(instance, dependencies);
}
}

No comments: