代码之家  ›  专栏  ›  技术社区  ›  Joshua Hayes

使用structuremap时如何对属性使用自定义注入属性?

  •  1
  • Joshua Hayes  · 技术社区  · 14 年前

    我希望拥有自己的注入属性,这样我就不会将代码耦合到特定的IOC框架。我有一个自定义的注入属性,我的代码使用它来表示应该注入一个属性。

    public class CustomInjectAttribute : Attribute {}
    

    下面是虚构的例子…

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

    在ninject中,您可以设置一个注入启发式方法来查找该属性,然后像这样注入;

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

    然后用内核注册启发式。

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

    我该如何用结构图来实现这一点呢?我知道structuremap有自己的setterproperties和属性,但是我正在寻找一种方法来从中分离出来,就像在上面的示例中使用ninject一样。

    1 回复  |  直到 14 年前
        1
  •  4
  •   Joshua Flanagan    14 年前

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

    public static bool HasAttribute<T>(this ICustomAttributeProvider provider) where T : Attribute
    {
        return provider.GetCustomAttributes(typeof (T), true).Any();
    }