如何注册使用温莎城堡一般的装饰? [英] How can I register a generic decorator using Castle Windsor?

查看:164
本文介绍了如何注册使用温莎城堡一般的装饰?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要装饰全部基于 ICommandHandler< T> 使用类型对应的 DeadlockRetryCommandHandlerDecorator< T> 键入

I need decorate all based onICommandHandler<T> types using a corresponding DeadlockRetryCommandHandlerDecorator<T> type

我试过这个解决方案,但不幸的是它不工作。

I tried this solution, but unfortunately it doesn't work.

container.Register(
    Component.For(typeof(ICommandHandler<>))
    .ImplementedBy(typeof(DeadlockRetryCommandHandlerDecorator<>)));

container.Register(
    AllTypes.FromThisAssembly()
        .BasedOn(typeof(ICommandHandler<>))
        .WithService.Base());

我如何注册一个通用的装饰( DeadlockRetryCommandHandlerDecorator&LT; T&GT; )来包装所有一般性的 ICommandHandler&LT; T&GT; 实现?

How can i register a generic decorator (DeadlockRetryCommandHandlerDecorator<T>) to wrap all generic ICommandHandler<T> implementations?

推荐答案

目前这种不支持开箱即用的,由于这样的事实,温莎总是在有利于模式的具体组件的开放式通用的。

currently this is not supported OOTB due to the fact that Windsor always favours mode specific component over an open-generic.

您可以得到与 ISubDependencyResolver 虽然工作很容易。下面的code假设你名称为您的装饰组件DeadlockRetryCommandHandlerDecorator

You can get that working quite easily with an ISubDependencyResolver though. The code below assumes you name the component for your decorator "DeadlockRetryCommandHandlerDecorator"

public class CommandHandlerResolver : ISubDependencyResolver
{
    private readonly IKernel kernel;

    public FooResolver(IKernel kernel)
    {
        this.kernel = kernel;
    }

    public bool CanResolve(CreationContext context, ISubDependencyResolver contextHandlerResolver, ComponentModel model, DependencyModel dependency)
    {
        return (dependency.TargetType.IsGenericType &&
                dependency.TargetType.GetGenericTypeDefinition() == typeof (ICommandHandler<>)) &&
                (model.Implementation.IsGenericType == false ||
                model.Implementation.GetGenericTypeDefinition() != typeof (DeadlockRetryCommandHandlerDecorator<>));
    }

    public object Resolve(CreationContext context, ISubDependencyResolver contextHandlerResolver, ComponentModel model, DependencyModel dependency)
    {
        return kernel.Resolve("DeadlockRetryCommandHandlerDecorator", dependency.TargetItemType);
    }
}

推荐实现的场景一样,与温莎的方式却是使用拦截器。

The recommended way of achieving scenarios like that with Windsor however is by using interceptors.

这篇关于如何注册使用温莎城堡一般的装饰?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆