Search code examples
c#.netcastle-windsor

passing part of constructor parameters to castle windsor container


I have constructor

Foo(IColor c , int someNumber)

and I know the some number only during the run time, and I want to call this constructor during the resolving and to pass someNumber value and the IColor to be resolved autocratically.

Something like this:

container.Resolve<IFoo>(someNumber);

Is it possible to be done ?


Solution

  • Yes, pass the constructor arguments in an instance of an anonymous type; the property names must match the constructor parameter names:

    IColor desiredColor = //whatever
    int desiredNumber = //whatever else
    IFoo foo = container.Resolve<IFoo>(new { c = desiredColor, somenumber = desiredArgumentValue });
    

    If you are using an older version of C# that does not support anonymous types (or even if you're not), you can do the same with a dictionary:

    IColor desiredColor = //whatever
    int desiredNumber = //whatever
    Dictionary<string, object> arguments = new Dictionary<string, object>();
    arguments.Add("c", desiredColor);
    arguments.Add("somenumber", desiredNumber);
    IFoo foo = container.Resolve<IFoo>(arguments);