Search code examples
c#castle-windsor

two string values for constructor using castle windsor


I am currently trying this:

var dependencies = new Dependency[2];
dependencies[0] = Dependency.OnValue("x", "xV");
dependencies[1] = Dependency.OnValue("y", "yV");
container.Register(
    Component.For<IBla>().ImplementedBy<BlaConcrete>().DependsOn(dependencies));

Unfortunately, it does not seem to work. The exception is:

Could not resolve non-optional dependency

The simplified concrete looks like this:

public class Bla : IBla
{
    private readonly string _x;
    private readonly string _y;

    public Bla(string x, string y)
    {
        _x = x;
        _y = y;
    }
]

Solution

  • There must be something else in your code causing the issue because in an empty project this code works as expected:

    static void Main(string[] args)
    {
        WindsorContainer container = new WindsorContainer();
        var dependencies = new Dependency[2];
        dependencies[0] = Dependency.OnValue("x", "xV");
        dependencies[1] = Dependency.OnValue("y", "yV");
        container.Register(Component.For<IBla>().ImplementedBy<Bla>().DependsOn(dependencies));
        var bla = container.Resolve<IBla>();
    }
    
    public interface IBla 
    {
    }
    
    public class Bla : IBla
    {
        readonly string _x;
        readonly string _y;
    
        public Bla(string x, string y)
        {
            _x = x;
            _y = y;
        }
    }
    

    Putting after breakpoint on the Resolve call shows that bla has "xV" and "yV" as values for its internal members.

    After you inspect the exception being thrown for more details (I promise there are more), I'd suggest removing parts of your application in pieces to see which has an effect on this. Alternatively, start from an empty project like this and add pieces of your application that might affect this.