通过参数名称解​​决 Castle Windsor 依赖

Resolve Castle Windsor dependency by argument name

鉴于此

Component.For<IService>().ImplementedBy<SecretService>().Named("secretService")
Component.For<IService>().ImplementedBy<PublicService>().Named("publicService")

class Foo{
    public Foo(IService publicService){ ...... }
}

class Bar{
    public Bar(IService secretService){ ...... }
}

那我怎样才能达到下面的效果呢

Foo 和 Bar 应该分别获得 publicService 和 secretService 的实例,完全基于它们的构造函数参数的名称。

我现在已经使用自定义 SubDependencyResolver 使其工作,我将其添加到容器中,现在它按名称注入实现

public class ByParameterNameResolver : ISubDependencyResolver
{
    private readonly IKernel kernel;

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

    public virtual bool CanResolve(CreationContext context, ISubDependencyResolver contextHandlerResolver, ComponentModel model, DependencyModel dependency)
    {
        if (dependency.TargetItemType == null)
            return false;

        if (string.IsNullOrWhiteSpace(dependency.DependencyKey))
            return false;

        return kernel.HasComponent(dependency.DependencyKey);
    }

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