如何使用PARAMETER构造函数注册registerType? [英] How to registerType with a PARAMETER constructor?

查看:64
本文介绍了如何使用PARAMETER构造函数注册registerType?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在类型没有参数构造函数的容器中注册类型。

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?

推荐答案

很简单。注册构造函数时,只需传递要为参数注入的值。容器根据值(API)或参数名称(XML)的类型来匹配您的构造函数。

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).

在API中,您需要执行以下操作:

In the API, you'd do:

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

这将选择一个采用单个字符串的构造函数,并在解析时将传递字符串 My

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

等效的XML(使用2.0配置模式)为:

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

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

这篇关于如何使用PARAMETER构造函数注册registerType?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆