37

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?

David Gardiner
  • 16,892
  • 20
  • 80
  • 117
Martin
  • 23,844
  • 55
  • 201
  • 327

2 Answers2

61

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>
Chris Tavares
  • 29,165
  • 4
  • 46
  • 63
  • What if i want multiple istance with different strings? – exSnake Jan 30 '23 at 23:49
  • Create two named registrations, with your two different strings, then resolve with the desired name for the particular use case. If you want something more complex, you're probably using a container incorrectly. – Chris Tavares Jan 31 '23 at 07:04
19

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.

N.N.
  • 8,336
  • 12
  • 54
  • 94
Brad
  • 191
  • 1
  • 2
  • new ResolvedParameter("MyConnectionString") but got an error The type String cannot be constructed. You must configure the container to supply this value, – Salman Jan 01 '20 at 07:21