4

How do I pass dynamic parameters to a UsingFactoryMethod registration?

For example, I want to write something like:

container.Register(
   Component.For<IFoo>()
        .UsingFactoryMethod(return DoSomethingAndReturnInstance(paremeter)));

I need the parameters to be sent at runtime, like this:

container.Resolve<IFoo>(new { parameter = value });

How can it be done?

Ilya Kogan
  • 21,995
  • 15
  • 85
  • 141

2 Answers2

7

CreationContext.AdditionalParameters has the values you pass to Resolve

Krzysztof Kozmic
  • 27,267
  • 12
  • 73
  • 115
3

You just have to use

container.Register(
    Component.For<IFoo>()
        .UsingFactoryMethod((kernel, creationContext) =>
        {
            var parameter = creationContext.AdditionalArguments["parameter"];
            return DoSomethingAndReturnInstance(parameter);
        }));