【问题标题】:Using DynamicProxy as a decorator pattern in windsor container在 Windsor 容器中使用 DynamicProxy 作为装饰器模式
【发布时间】:2010-10-07 23:19:27
【问题描述】:

我正在寻找有关使用和配置 Windsor 以提供动态代理来拦截对另一个类的实例的调用的一些信息。

我的类代表一种资源,出于性能原因,该资源应由容器作为长期存在的实例保留。但是,有时此资源可能会转变为不可用状态,并且需要更新。我希望容器来处理这个,所以客户端代码不必这样做。我可以创建自己的工厂来执行此操作,我想知道是否有一些温莎注册很酷可以为我做这件事,所以我不必创建单独的工厂类:)

这里有一些伪代码来演示这个问题:

public interface IVeryImportantResource
{
    void SomeOperation();
}

public class RealResource : IVeryImportantResource
{
    public bool Corrupt { get; set; }

    public void SomeOperation()
    {
        //do some real implementation
    }
}

public class RealResourceInterceptor : IInterceptor
{
    private readonly IKernel kernel;

    public RealResourceInterceptor(IKernel Kernel)
    {
        kernel = Kernel;
    }

    public void Intercept(IInvocation invocation)
    {
        RealResource resource = invocation.InvocationTarget as RealResource;

        if(resource.Corrupt)
        {
            //tidy up this instance, as it is corrupt
            kernel.ReleaseComponent(resource);
            RealResource newResource = kernel.Resolve<RealResource>(); //get a new one
            //now what i would like to happen is something like this
            //but this property has no setter, so this doesn't work
            //also, i would like to know how to register RealResourceInterceptor as well RealResourceInterceptor
            invocation.InvocationTarget = newResource;
        }
        invocation.Proceed();
    }
}

任何想法如何实现我的 RealResourceInterceptor 类,以及如何配置容器以使用它?谢谢!

【问题讨论】:

    标签: inversion-of-control castle-windsor decorator castle-dynamicproxy


    【解决方案1】:

    这个问题更多是关于更新单例组件而不是拦截。更新单例的问题在this question回答。

    底线:这并不像看起来那么容易,这种方法存在许多陷阱。

    也许问题在于这个组件被损坏了(为什么会这样?)

    【讨论】:

    • 使用城堡设施是前进的方向
    【解决方案2】:

    我的对象是 WCF 代理。这些对象将转换为故障状态,使它们无法使用。我无法控制他们何时或是否会过渡。我只能检测到它已经发生,并重新创建一个新的代理。

    感谢您的链接,下面引用的部分大致描述了我目前的操作方式:

    另外一种方法是 为您服务的装饰师 在容器中注册 单身的生活方式,但你的实际 注册的底层服务 具有短暂生活方式的容器 - 那么当你需要刷新 组件只是处置 瞬态底层组件由 装饰器并将其替换为 新解决的实例(解决它 使用 components 键,而不是 服务,以避免得到 装饰器) - 这避免了问题 其他单例服务(不是 被“刷新”)从坚持 已经过时的服务 处理使它们无法使用,但 确实需要一些铸造等 让它工作

    我的问题是,而不是这些:

    1) 使用静态类型的装饰器来包装我的 RealResource(如上)。一旦你获得了许多这样的代理,为它们创建装饰器就变得很痛苦。

    2) 使用创建动态代理的工厂对象来管理任何 WCF 代理的状态。

    2) 是远远优于但似乎温莎可能已经能够为我做的事情。所以,我想知道是否有任何容器 automagic,它可以让我在配置时注册一个拦截器,而不是创建自己的工厂?

    类似这样的伪代码:

    container.AddComponent("dynamicProxyWrapper", typeof(IRealResource), typeof(RealResource)).UsingInterceptor(typeof(RealResourceInterceptor));
    

    【讨论】:

    猜你喜欢
    • 2013-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-01
    • 1970-01-01
    • 2012-09-20
    • 2010-12-05
    相关资源
    最近更新 更多