Night Walker
Night Walker

Reputation: 21260

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 ?

Upvotes: 9

Views: 10990

Answers (2)

Aleš Roub&#237;ček
Aleš Roub&#237;ček

Reputation: 5187

You should prefer Typed Factory instead of using container like service locator. Just define factory interface:

public interface IFooFactory {
    IFoo Create(int somenumber);
}

and register it as typed factory:

container.Register(Component.For<IFooFactory>().AsFactory());

Then use dependency injection to inject factory and use it:

var foo = fooFactory.Create(desiredArgumentValue);

For more info read Windsor documentation

Upvotes: 18

phoog
phoog

Reputation: 43046

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

Upvotes: 10

Related Questions