A few years ago I blogged about how to add Lazy Unity Injection, and then a year after that Unity 3 added that feature. Recently I had to dust off this old code to do something similar...
I wanted to use Unity to inject a collection of registered types into one of my services. To do this directly from the container you would use named registrations and ResolveAll. However if you just try to resolve an IEnumerable of a type in a constructor, then Unity will just try to use Resolve and thus throw an InvalidOperationException.
We can easily "fix" this by registering an extension with our container.
Extension
public class EnumerableContainerExtension : UnityContainerExtension
{
protected override void Initialize()
{
Context.Policies.Set<IBuildPlanPolicy>(
new EnumerableBuildPlanPolicy(),
typeof(IEnumerable<>));
}
private class EnumerableBuildPlanPolicy : IBuildPlanPolicy
{
public void BuildUp(IBuilderContext context)
{
if (context.Existing != null)
return;
var container = context.NewBuildUp<IUnityContainer>();
var typeToBuild = context.BuildKey.Type.GetGenericArguments()[0];
context.Existing = container.ResolveAll(typeToBuild);
DynamicMethodConstructorStrategy.SetPerBuildSingleton(context);
}
}
}