使用属性注入

时间:2014-09-08 17:47:28

标签: c# reflection attributes

我不确定这是什么,但这就是我想要实现的目标:

我需要能够为属性,字段和类指定属性,并且每次指定了[Attribute]的对象都会调用某个静态函数。

我已经知道如何设置属性,但我不知道如何拦截每个对象的创建并调用它上面的函数。

1 个答案:

答案 0 :(得分:3)

如果没有在类本身中插入某种代码,或者在类周围创建Factory来管理实例化,则无法拦截正在创建的对象。

假设您有这样的课程:

public class MyData
{
    [Captialization]
    public string Name { get; set; }
}

使用如下定义的属性:

[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Class)]
public class CaptializationAttribute : Attribute { }

您可以检测和操作标记有各种属性的属性,如下所示:

public static class DataUtilities
{
    public static void ApplyAttributes<T>(T obj)
    {
        // Capitalization attribute
        var props = typeof (T).GetProperties().Where(p => p.GetCustomAttributes(typeof (CaptializationAttribute), true).Any());
        foreach (var prop in props)
        {
            // This is just an example, if you use this code you 
            // should check if the property is a string first!

            prop.SetValue(obj, prop.GetValue(obj).ToString().ToUpper());

            // Or perform some other manipulation here.
        }
    }
}

现在,要自动调用此代码,您需要决定何时发生此代码。如果在实例化后它很好,你可能不得不从某个地方自己调用它。但是如果它在实例化期间,你可以做以下两件事之一:

使用工厂:

public static class MyDataFactory
{
    public static MyData Create()
    {
        var myData = new MyData();
        DataUtilities.ApplyAttributes(myData);
        return myData;
    }
}

您可能希望使用内部构造函数来防止外部实例化。

// No instantiation from outside the assembly
internal MyData() { }

使用构造函数:

将对操纵实用程序的调用添加到构造函数中:

public MyData()
{
    DataUtilities.ApplyAttributes(this);
}

还有其他方法可以执行此操作,例如使用ProxyDependency Injection@Yuval Itzchakov提及AOP framework,但我所描述的可能是最容易实施。

相关问题