在Simple Injector中调用拦截的方法调用函数

时间:2014-08-22 11:33:30

标签: c# simple-injector interception

我想要实现的是拦截类的注入,并在类上调用特定的方法来改变它的行为。

我已经实现了SimpleInjector网站上提供的interceptor class,这是有效的,所以我可以在拦截类时运行一些功能。

我的容器正在注册:

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实例

2 个答案:

答案 0 :(得分:3)

为什么不使用装饰器而不是使用拦截?这通常更容易,更易于维护和更快。

以下是一个例子:

public class PropSetMyClassDecorator : IMyClass
{
    private MyClass decoratee;
    public PropSetMyClassDecorator(MyClass decoratee) {
        this.decoratee = decoratee;
    }

    public void MethodToCall() {
        this.decoratee.SetConnectionString();
        this.decoratee.MethodToCall();
    }
}

您可以按如下方式注册此装饰器:

container.Register<IMyClass, PropSetMyClassDecorator>();

请注意,我们只注册装饰器,而不是注册MyClass。由于装饰器直接依赖于MyClas s(不在界面上)MyClass将由Simple Injector自动解析。

另一个选择是按如下方式注册初始化程序:

container.RegisterInitializer<MyClass>(instance => {
    instance.SetConnectionString();
});

每次构造MyClass实例后,都会调用初始化程序委托。在这种情况下,行为有点不同,因为每次都不调用该方法,而是仅在构造期间调用。但通常情况下,这应该足够了,因为您通常不应该在运行时更改服务,因为这会使事情变得复杂。

答案 1 :(得分:2)

好的,在发布问题后不久就找到了解决方案。

我将Intercept函数更改为以下内容:

    public void Intercept(IInvocation invocation)
    {
        // Calls the decorated instance.
        invocation.Proceed();

        var classIntercepted = invocation.InvocationTarget;
        MethodInfo method = invocation.InvocationTarget.GetType().GetMethod("SetConnectionString");
        method.Invoke(classIntercepted, null);
    }