Combining attribute based and configured injection

Dec 16, 2008 at 3:32 PM

Consider the following example:

using Microsoft.Practices.Unity;

public class Program {
    public static void Main() {
        IUnityContainer container = new UnityContainer()
            .RegisterType<IComponent, Component>("First")
            .RegisterType<IComponent, Component>("Second", new InjectionMethod("SecondMethod"));

        IComponent first = container.Resolve<IComponent>("First");
        IComponent second = container.Resolve<IComponent>("Second");
public interface IComponent {
    void FirstMethod();
    void SecondMethod();
public class Component : IComponent {
    public void FirstMethod() { }
    public void SecondMethod() { }

If the “first” component is resolved only the “FirstMethod” gets called.
If the “second” component is resolved only the “SecondMethod” gets called. The “FirstMethod” marked with the attribute isn’t called.

In the implementation of the “InjectionMethod” class the DefaultMethodSelectorPolicy gets replaced by the SpecifiedMethodSelectorPolicy. Both policies allow to specify multiple methods to be called. Why does the SpecifiedMethodSelectorPolicy not also search for methods marked with the Injection attribute?
Is this by design or a possible bug?

Thanks for any suggestions

Dec 16, 2008 at 7:46 PM
It is by design. The assumption is that if you're manually configuring injection, you know exactly what you want called, and may need to override the attribute if you want to turn it off. The easiest to understand way to do this was to have the manual configuration override the attributes.