【问题标题】:Castle Windsor Proxy Abstract Class with Interface带接口的 Castle Windsor 代理抽象类
【发布时间】:2011-05-23 21:21:43
【问题描述】:

我有以下场景:

public interface IFoo 
{
    void Foo1();

    void Foo2(); 
}

public abstract class Foo : IFoo
{
    public void Foo1() { }

    public abstract void Foo2();
}

我想为 IFoo 注册一个服务,由 Foo 实现,但使用拦截器来处理对未实现抽象成员的调用。所以,我可以这样做:

container.Register(Component.For<IFoo>()
.ImplementedBy<Foo>().Interceptors<MyInterceptor>());

但我在尝试激活我的组件时遇到以下异常:

"Instances of abstract classes cannot be created."

   at Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.CreateInstance(CreationContext context, Object[] arguments, Type[] signature)
   at Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.Instantiate(CreationContext context)
   at Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.InternalCreate(CreationContext context)
   at Castle.MicroKernel.ComponentActivator.AbstractComponentActivator.Create(CreationContext context)
   at Castle.MicroKernel.Lifestyle.AbstractLifestyleManager.Resolve(CreationContext context)
   at Castle.MicroKernel.Handlers.DefaultHandler.ResolveCore(CreationContext context, Boolean requiresDecommission, Boolean instanceRequired)
   at Castle.MicroKernel.Handlers.AbstractHandler.Resolve(CreationContext context, Boolean instanceRequired)
   at Castle.MicroKernel.Handlers.AbstractHandler.Resolve(CreationContext context)
   at Castle.MicroKernel.Resolvers.DefaultDependencyResolver.ResolveServiceDependency(CreationContext context, ComponentModel model, DependencyModel dependency)

我注意到以下工作成功....

Component.For<Foo>().Forward<IFoo>().Interceptors<MyInterceptor>()

但是我的拦截器最终在拦截时看到 Foo,而不是 IFoo 作为 TargetType...这不是我想要的。

关于如何完成此任务的任何建议?

谢谢。

【问题讨论】:

    标签: c# .net castle-windsor castle-dynamicproxy


    【解决方案1】:

    我想如果你指定:

    Component.For<IFoo, Foo>().Interceptors<MyInterceptor>()
    

    这会起作用。

    您最初遇到此问题的原因是,Windsor 为服务(即接口)而不是类(不是服务)创建了代理,并且它试图正常实例化类,这显然是不可能的,如果类是抽象的。

    这就是为什么如果您也将类指定为服务,该类也将被代理,并且整个事情都会起作用。

    关于你的最后一句话,你不能一边吃蛋糕一边吃。如果你想代理类,那么类就是代理的目标。

    【讨论】:

    • 如果我执行上述操作(本质上将 Foo 指定为转发),Foo 的实现似乎并没有进入那里......所以当我调用 Foo2() 然后我的拦截器尝试调用 invocation.Proceed,我得到:这是一个 DynamicProxy2 错误:拦截器试图为没有目标的方法 'Void Foo2()' 'Proceed'。
    • 对。这提醒我,这里的排序可能很重要。我记得修复了这个问题,所以顺序无关紧要,但也许它只是后备箱。无论如何-如果您在注册时交换订单应该没问题。
    • 所以 Component.For?这不会阻止服务类型成为 IFoo 吗?还是我误会了?
    • 不,您将同时拥有IFooFoo 作为服务。至少这是我的理解
    猜你喜欢
    • 2011-05-02
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-01
    • 2011-01-20
    相关资源
    最近更新 更多