统一拦截概念清晰度

时间:2014-01-27 10:18:55

标签: c# unity-container unity-interception

我正在关注Unity Interception链接,在我的项目中实现Unity。

通过链接,我创建了一个类,如下所示:

[AttributeUsage(AttributeTargets.Method)]
public class MyInterceptionAttribute : Attribute
{

}

public class MyLoggingCallHandler : ICallHandler
{
    IMethodReturn ICallHandler.Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
    {
        IMethodReturn result = getNext()(input, getNext);
        return result;
    }
    int ICallHandler.Order { get; set; }
}

public class AssemblyQualifiedTypeNameConverter : ConfigurationConverterBase
{
    public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
    {
        if (value != null)
        {
            Type typeValue = value as Type;
            if (typeValue == null)
            {
                throw new ArgumentException("Cannot convert type", typeof(Type).Name);
            }
            if (typeValue != null) return (typeValue).AssemblyQualifiedName;
        }
        return null;
    }

    public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
    {
        string stringValue = (string)value;
        if (!string.IsNullOrEmpty(stringValue))
        {
            Type result = Type.GetType(stringValue, false);
            if (result == null)
            {
                throw new ArgumentException("Invalid type", "value");
            }
            return result;
        }
        return null;
    }
}

直到现在我没有做任何特别的事情,只是按照上面链接中的说明进行了操作。但是,当我必须实现Unity Interception类时,我提出了很多困惑。

假设,我必须在我的类中的一个方法上实现,如:

[MyInterception]
public Model GetModelByID(Int32 ModelID)
{
    return _business.GetModelByID(ModelID);
}

这是我被卡住的主要原因,我不知道如何使用Intercept类而不是 GetModelByID()方法以及如何获得统一性。

请帮助我,并请解释Unity拦截的概念。

1 个答案:

答案 0 :(得分:0)

Unity拦截解释

拦截是一个概念,您可以将“核心”代码与其他问题隔离开来。在你的方法中:

public Model GetModelByID(Int32 ModelID)
{
   return _business.GetModelByID(ModelID);
}

你不想用日志,分析,缓存等其他代码“污染”它,这不是方法的核心概念的一部分,统一拦截将帮助你解决这个问题。

通过拦截,您可以向现有代码添加功能,而无需触及实际代码!

您的具体问题

  

如果我的_business为null,那么不应该调用GetModelById(),我该如何实现呢?

通过使用拦截和反射,您实际上可以实现您想要做的事情。我现在无法访问开发环境,但这样的事情应该可行,

IMethodReturn ICallHandler.Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
{
    IMethodReturn result = input.CreateMethodReturn(null, new object[0]);

    var fieldInfos = input.Target.GetType().GetFields(BindingFlags.Instance | BindingFlags.NonPublic);
    var businessField = fieldInfos.FirstOrDefault(f => f.Name == "_business");

    if (businessField != null && businessField.GetValue(input.Target) != null)
        result = getNext()(input, getNext);

    return result;
}

您可以访问方法(您正在拦截的方法)所属的目标(对象),然后通过反射读取该对象私有字段的值。

相关问题