开发者

How to registerType with a PARAMETER constructor?

开发者 https://www.devze.com 2023-01-21 20:19 出处:网络
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 repre开发者_如何学Gosents

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 repre开发者_如何学Gosents a Path.

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


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>


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号