How to registerType with a PARAMETER constructor?

Martin picture Martin · Oct 23, 2010 · Viewed 35.3k times · Source

How do I registertype with the container where the type doesn't have NO PARAMETER constructor.

In fact my constructor accepts a string, and I normally pass in a string that represents a Path.

So when I do resolve it automatically creates the new type but passing in a string?

Answer

Chris Tavares picture Chris Tavares · Oct 24, 2010

It's simple. When you register the constructor, you just pass the value you want injected for the parameter. The container matches up your constructor based on the type of value (API) or name of parameter (XML).

In the API, you'd do:

container.RegisterType<MyType>(new InjectionConstructor("My string here"));

That will select a constructor that takes a single string, and at resolve time will pass the string "My string here".

The equivalent XML (using the 2.0 config schema) would be:

<register type="MyType">
  <constructor>
    <param name="whateverParameterNameIs" value="My string here" />
  </constructor>
</register>