1

我在使用 Castle Windsor ISubDependencyResolver 获取参数名称时遇到了一点问题。我有类似下面的代码,对于 Foo,我希望 myBar.BarName 为“Foo_myBar”

Public Class Foo
{
    private readonly IBar myBar;
    Public Foo(IBar myBar){
        this.myBar = myBar;
    }
}

Public Class Bar: IBar
{
    Public string BarName {get; private set;}

    Public Bar(string barName){
        BarName = barName;
    }
}

public class BarNameResolver : ISubDependencyResolver
{
    public bool CanResolve(CreationContext context, 
            ISubDependencyResolver contextHandlerResolver, 
            ComponentModel model, 
            DependencyModel dependency)
    {
        return context.RequestedType == typeof (IBar)
               && dependency.TargetType == typeof (string)
               && dependency.DependencyKey.Equals("barName");
    }

    public object Resolve(CreationContext context, 
            ISubDependencyResolver contextHandlerResolver, 
            ComponentModel model,
            DependencyModel dependency)
    {

        return string.Format("{0}_{1}", 
                  context.Handler.ComponentModel.Name, 
                  **NameOfFooBarParameter**);


    }
}

有什么方法可以在 ISubDependencyResolver 中获取“myBar”?

我需要这个在 Foo 中有多个具有不同配置的 IBar 实例。

4

1 回答 1

1

由于 BarNameResolver 是一个子依赖解析,因此很容易混淆组件和依赖项

public bool CanResolve(
   CreationContext context,
   ISubDependencyResolver contextHandlerResolver,
   ComponentModel model,
   DependencyModel dependency)
   {
       return context.RequestedType == typeof(Foo)
           && dependency.TargetType == typeof(IBar);
   }

   public object Resolve(
       CreationContext context,
       ISubDependencyResolver contextHandlerResolver,
       ComponentModel model,
       DependencyModel dependency)
       {
            var myBar  = dependency.DependencyKey;
            return null;
       }

在您的示例中,变量 myBar 现在将包含字符串“myBar”。您可以使用它来解决依赖关系。

于 2013-03-19T16:30:46.130 回答