Castle Windsor ISubDependencyResolver get name of parameter

971 Views Asked by At

I have a little problem getting the name of a parameter using Castle Windsor ISubDependencyResolver. I have something like the code below, and in the case of Foo, I would like myBar.BarName to be "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**);


    }
}

Is the any way to get "myBar" in ISubDependencyResolver?

I need this to have multiple instances of IBar in Foo with different configurations.

1

There are 1 best solutions below

0
On

Since BarNameResolver is a subdepedency resolve it is easy to mix up the component and dependency

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;
       }

In your example the variable myBar will now contain the string "myBar". You can use this to resolve the dependency.