如何使用 Castle Windsor 注册通用装饰器? [英] How can I register a generic decorator using Castle Windsor?

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

问题描述

我需要使用相应的 DeadlockRetryCommandHandlerDecorator 类型来装饰所有基于 ICommandHandler 类型的类型

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)来包装所有通用的 ICommandHandler 实现?

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

推荐答案

目前不支持 OOTB,因为 Windsor 总是偏爱特定于模式的组件而不是开放式泛型.

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

不过,您可以使用 ISubDependencyResolver 轻松实现这一点.下面的代码假设您为装饰器命名组件 "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);
    }
}

推荐实现类似 Windsor 场景的方法是使用拦截器.

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

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

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