views:

20

answers:

1

I would like to have my own injection attribute so that I am not coupling my code to a particular IOC framework. I have a custom injection attribute that my code uses to denote that a property should be injected.

public class CustomInjectAttribute : Attribute {}

Fictitious example below...

public class Robot : IRobot
{
   [CustomInject]
   public ILaser Zap { get; set; }

   ...
}

In Ninject, you can setup an injection Heuristic to find that attribute, and inject like;

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

and then register the heuristic with the kernel.

Kernel.Components.Get<ISelector>().InjectionHeuristics.Add(new NinjectInjectionHeuristic());

How would I go about achieving this with StructureMap. I know StructureMap has its own SetterProperties and attributes, but I'm looking for a way to decouple from that as you can with Ninject in the above example.

+2  A: 

Use the SetAllProperties() method in your ObjectFactory or Container configuration. For example:

new Container(x =>
{
    x.SetAllProperties(by =>
    {
        by.Matching(prop => prop.HasAttribute<CustomInjectAttribute>());
    });
});

This makes use of a handy extension method (that should be in the BCL):

public static bool HasAttribute<T>(this ICustomAttributeProvider provider) where T : Attribute
{
    return provider.GetCustomAttributes(typeof (T), true).Any();
}
Joshua Flanagan
That's exactly what I was after. Thanks!
Joshua Hayes