How to registerType with a PARAMETER constructor?

38,220

Solution 1

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>

Solution 2

You can also use the built in InjectionConstructor and ResolvedParameter where connectionString is the database connection string to be used.

// install a named string that holds the connection string to use
container.RegisterInstance<string>("MyConnectionString", connectionString, new ContainerControlledLifetimeManager()); 

// register the class that will use the connection string
container.RegisterType<MyNamespace.MyObjectContext, MyNamespace.MyObjectContext>(new InjectionConstructor(new ResolvedParameter<string>("MyConnectionString")));

var context = container.Resolve<MyNamespace.MyObjectContext>();

You could take it even one step further and have multiple named instances of MyObjectContext, each using their own connection string to different databases.

Share:
38,220
Martin
Author by

Martin

Updated on February 02, 2022

Comments

  • Martin
    Martin over 2 years

    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?

  • Salman
    Salman over 4 years
    new ResolvedParameter<string>("MyConnectionString") but got an error The type String cannot be constructed. You must configure the container to supply this value,