Reputation: 1705
I have a IInterceptionBehavior like blow:
public class TraceBehavior : IInterceptionBehavior
{
public IEnumerable<Type> GetRequiredInterfaces()
{
return Type.EmptyTypes;
}
public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
{
Console.WriteLine(string.Format("Invoke method:{0}",input.MethodBase.ToString()));
IMethodReturn result = getNext()(input, getNext);
if (result.Exception == null)
{
Console.WriteLine("Invoke successful!");
}
else
{
Console.WriteLine(string.Format("Invoke faild, error: {0}", result.Exception.Message));
result.Exception = null;
}
return result;
}
public bool WillExecute { get { return true; } }
}
Regardless of whether I put it upon methods or not, exception throw always. Anyone can help me?
Upvotes: 4
Views: 1344
Reputation: 22655
The code looks OK but you haven't shown how the interception is registered and how the object is being called.
Assuming that interception is being called then if I were to guess it would be that that the method invoked returns a value type and IMethodReturn.ReturnValue
is null which is causing a NullReferenceException
.
If that is the case then perhaps returning the default value for a value type would solve your issue:
public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
{
Console.WriteLine(string.Format("Invoke method:{0}", input.MethodBase.ToString()));
IMethodReturn result = getNext()(input, getNext);
if (result.Exception == null)
{
Console.WriteLine("Invoke successful!");
}
else
{
Console.WriteLine(string.Format("Invoke faild, error: {0}", result.Exception.Message));
result.Exception = null;
Type type = ((MethodInfo)input.MethodBase).ReturnType;
if (type.IsValueType)
{
result.ReturnValue = Activator.CreateInstance(type);
}
}
return result;
}
Upvotes: 4