dependency-injectionioc-containerninjectninject-2

Ninject 2.0: Property Injection without attribute


Is there a way to use Property Injection in Ninject 2 without using the [Inject] attribute? This creates a dependency to Ninject in the class that will be wired using it and I prefer to avoid having unneeded dependencies to my IoC container, that's why I end up using Constructor Injection more often.

I guess the same applies to Method Injection


Solution

  • I followed Ruben's tip and posted a small blog post on how to achieve this, but here's the quick answer:

    Create a custom attribute:

    public class InjectHereAttribute : Attribute
    {
    }
    

    The target class will now look like this:

    public class Samurai
    {
        [InjectHere]        
        public IWeapon Context { get; set; }
    }
    

    Now Ninject must be configured to use the custom attribute, this can be done by creating an implementation of IInjectionHeuristic that recognizes the custom attribute:

    public class CustomInjectionHeuristic : NinjectComponent, IInjectionHeuristic, INinjectComponent, IDisposable
    {
        public new bool ShouldInject(MemberInfo member)
        {
            return member.IsDefined(
              typeof(InjectHereAttribute),
              true);
        }
    }
    

    And finally add this behavior to the Ninject Kernel using the Components collection, it will run along the existing components, namely the default implementation of IInjectionHeuristic, which means either the default or the custom attribute can be used.

    // Add custom inject heuristic
    kernel.Components.Add<IInjectionHeuristic, CustomInjectionHeuristic>();