Dependency Selection

Mar 24, 2008 at 10:39 PM
Edited Mar 24, 2008 at 11:07 PM
I'm trying to understand this concept:

I have one object:
public MainObject( IDependency dependency )

Let's say I register 2 IDependencys: DependencyA (with a buildname of null) and DependencyB (with a buildname of "B")

If I call IUnityContainer.Resolve<MainObject>() it will inject my registered instance of DependencyA. How do I go about getting it to use my instance of DependencyB when I call IUnityContainer.Resolve<MainObject>( "B" )?
Mar 25, 2008 at 12:06 AM
You are correct that the names don't "flow" through dependency resolution. The name for each dependency is evaluated independently, based on your current configuration or the attributes you specify. This fits the expected usage pattern of the container: You may be building the named database "Northwind" but you still want to use the default logger, not the "Northwind" logger that doesn't exist.

You can't make them flow out of the box, but you could write a custom resolver/attribute/extension to allow that to happen. If you're interested let me know.

Mar 25, 2008 at 1:31 AM


ctavares wrote:
You can't make them flow out of the box, but you could write a custom resolver/attribute/extension to allow that to happen. If you're interested let me know.


Actually the new InjectionConfiguration in today's drop looks EXACTLY what I was looking for! Very cool. However, it doesn't appear the TypeInjectionElement doesn't ConfigureInjectionFor buildnames. :(
Mar 25, 2008 at 1:57 AM
Edited Mar 25, 2008 at 2:24 AM
I agree.

AFAIK, TypeInjectionElement should either have a Name property so that it can configure injection according to a named build key or reuse the Name from its parent UnityTypeElement (parent would have to be available, of course!)
Mar 25, 2008 at 3:30 AM
It should be reusing the name from the parent <type> element. If it isn't, there's a bug.
Mar 25, 2008 at 4:57 AM
Edited Mar 25, 2008 at 4:58 AM
I just checked the code, and yep, there's a bug (and a hole in the unit test coverage).

The fix is to change Source\Unity\Src\Unity.Configuration\ConfigurationElements\ContainerElement\TypesElement\TypeInjectionElement\TypeInjectionElement.cs, line 48, to:

.ConfigureInjectionFor(targetType, ParentElement.Name, injections.ToArray());

(The existing version doesn't pass ParentElement.Name.)
Mar 25, 2008 at 1:01 PM
Just to be sure, I've noticed that the ConfigurationAPI returns an empty string for a null value, so I've been setting up my configuration properties to check for this condition. So in the above case, we really need to check for: !string.IsNullOrEmpty( ParentElement.Name ) ? ParentElement.Name : null (I wish there was a ?? for this...)
Mar 25, 2008 at 5:22 PM
We don't need to check for null here; the build key code treats "" the same as null. Otherwise we'd need a lot more string.IsNullOrEmpty checks. :-)