5 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;
}
}
Run Code Online (Sandbox Code Playgroud)
直到现在我没有做任何特别的事情,只是按照上面链接中的说明进行了操作.但是,当我必须实现Unity Interception类时,我提出了很多困惑.
假设,我必须在我的类中的一个方法上实现,如:
[MyInterception]
public Model GetModelByID(Int32 ModelID)
{
return _business.GetModelByID(ModelID);
}
Run Code Online (Sandbox Code Playgroud)
这是我被卡住的主要问题,我不知道如何使用Intercept类而不是GetModelByID()方法以及如何获得统一性.
请帮助我,并请解释Unity拦截的概念.
Unity拦截解释
拦截是一个可以将“核心”代码与其他问题隔离开来的概念。在你的方法中:
public Model GetModelByID(Int32 ModelID)
{
return _business.GetModelByID(ModelID);
}
Run Code Online (Sandbox Code Playgroud)
您不想用其他代码(例如日志记录、分析、缓存等)“污染”它,这不是该方法的核心概念的一部分,统一拦截将帮助您解决此问题。
通过拦截,您可以向现有代码添加功能,而无需接触实际代码!
您的具体问题
如果我的 _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;
}
Run Code Online (Sandbox Code Playgroud)
您可以访问方法(您正在拦截的方法)所属的目标(对象),然后通过反射读取该对象私有字段的值。
| 归档时间: |
|
| 查看次数: |
469 次 |
| 最近记录: |