城堡温莎拦截器

时间:2015-04-15 13:18:48

标签: c# .net dependency-injection castle-windsor interception

我尝试使用此页面中的代码http://docs.castleproject.org/Windsor.Introduction-to-AOP-With-Castle.ashx并以流畅的方式注册拦截器。 但是我抛出了这个错误。我尝试过Castle Windsor版本从2.5到3.3。因此,拦截器的设置必须是非常基础的东西

public interface ISomething
{
    Int32 Augment(Int32 input);
    void DoSomething(String input);
    Int32 Property { get; set; }
}

class Something : ISomething
{
    public int Augment(int input) {
        return input + 1;
    }

    public void DoSomething(string input) {
        Console.WriteLine("I'm doing something: " + input);
    }

    public int Property { get; set; }
 }

public class DumpInterceptor : IInterceptor
{
    public void Intercept(IInvocation invocation) {
        Console.WriteLine("DumpInterceptorCalled on method " +
            invocation.Method.Name);
        invocation.Proceed();

        if (invocation.Method.ReturnType == typeof(Int32)) {
            invocation.ReturnValue = (Int32)invocation.ReturnValue + 1;
        }

        Console.WriteLine("DumpInterceptor returnvalue is " +
            (invocation.ReturnValue ?? "NULL"));
    }     
}

设置

Console.WriteLine("Run 2 - configuration fluent");
using (WindsorContainer container = new WindsorContainer())
{
    container.Register(
        Component.For<IInterceptor>()
        .ImplementedBy<DumpInterceptor>()
        .Named("myinterceptor"));
    container.Register(
        Component.For<ISomething>()
        .ImplementedBy<Something>()
     .Interceptors(InterceptorReference.ForKey("myinterceptor")).Anywhere);


    ISomething something = container.Resolve<ISomething>(); //Offending row

    something.DoSomething("");

    Console.WriteLine("Augment 10 returns " + something.Augment(10));
}

错误

  

键入&#39; Castle.Proxies.ISomethingProxy&#39;从   assembly&#39; DynamicProxyGenAssembly2,Version = 0.0.0.0,Culture = neutral,   公钥=空&#39;正试图实现无法访问   接口

1 个答案:

答案 0 :(得分:0)

答案

所以我发现为什么会这样。显然,如果您创建内部类和接口,您可以注册并解决它们,但是将拦截器附加到它们将无法正常工作

示例 - 将触发错误

class Program
{
    public static void Main(String [] args)
    {
        var container = new WindsorContainer();
        container.Register(Component.For<TestInterceptor>().Named("test"));
        container.Register(Component.For<InnerInterface>().ImplementedBy<InnerClass>().Interceptors(InterceptorReference.ForKey("test")).Anywhere);
        // this row below will throw the exception
        var innerClassInstance = container.Resolve<InnerInterface>();
    }

    class InnerClass : InnerInterface  { }

    interface InnerInterface { }

    class TestInterceptor : IInterceptor
    {
        public void Intercept(IInvocation invocation)
        {
            throw new NotImplementedException();
        }
    }
}

结论

因此,总而言之,我的目的不是首先创建内部类,而是组装一个演示来展示Castle Windsor。但也许这可以帮助某人,如果他们遇到与我相同的错误..