我想要实现的是拦截一个类的注入,并在该类上调用一个特定的方法来改变它的行为。
我已经实现了SimpleInjector 网站上给出的拦截器类,并且这是有效的,所以当类被拦截时我能够运行一些功能。
我的容器正在这样注册它:
container.InterceptWith<MyInterceptor>(type => type == typeof(IMyClass));
我拦截的课程如下所示:
public class MyClass : IMyClass
{
private IAnotherClass m_class;
public MyClass(IAnotherClass _class)
{
m_class = _class;
}
public void MethodToCall()
{
//changes properties on class
}
}
我的拦截器类如下所示:
public class MyInterceptor : IInterceptor
{
private readonly ILogger logger;
public MyInterceptor(ILogger logger)
{
this.logger = logger;
}
public void Intercept(IInvocation invocation)
{
var watch = Stopwatch.StartNew();
// Calls the decorated instance.
invocation.Proceed();
var decoratedType = invocation.InvocationTarget.GetType();
logger.Trace(string.Format("{0} executed in {1} ms.",
decoratedType.Name, watch.ElapsedTicks));
}
}
我想要实现的是在拦截的 IMyClass 上调用一个方法。所以在拦截器中,调用MyClass.MethodToCall()
我试图在Intercept()
方法中做这样的事情:
var classIntercepted = invocation.ReturnValue;
MethodInfo method = invocation.InvocationTarget.GetType().GetMethod("MethodToCall");
object magicValue = method.Invoke(classIntercepted, null);
但是,invocation.ReturnValue
不是返回MyClass
实例,而是返回IAnotherClass
实例