Dependency injection 如何使用参数构造函数注册类型?

Dependency injection 如何使用参数构造函数注册类型?,dependency-injection,unity-container,ioc-container,Dependency Injection,Unity Container,Ioc Container,如何在类型没有参数构造函数的容器中注册类型 事实上,我的构造函数接受一个字符串,我通常传入一个表示路径的字符串 因此,当我解析时,它会自动创建新类型,但会传入一个字符串?这很简单。注册构造函数时,只需传递要为参数注入的值。容器根据值类型(API)或参数名称(XML)匹配构造函数 在API中,您将执行以下操作: container.RegisterType<MyType>(new InjectionConstructor("My string here")); container.R

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

事实上,我的构造函数接受一个字符串,我通常传入一个表示路径的字符串


因此,当我解析时,它会自动创建新类型,但会传入一个字符串?

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

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

container.RegisterType<MyType>(new InjectionConstructor("My string here"));
container.RegisterType(新的InjectionConstructor(“此处为我的字符串”);
这将选择一个接受单个字符串的构造函数,并在解析时传递字符串“MyString here”

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

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

您还可以使用内置的InjectionConstructor和ResolvedParameter,其中connectionString是要使用的数据库连接字符串

// 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>();
//安装包含要使用的连接字符串的命名字符串
RegisterInstance(“MyConnectionString”,connectionString,new ContainerControlled LifetimeManager());
//注册将使用连接字符串的类
RegisterType(新注入构造函数(新解析参数(“MyConnectionString”));
var context=container.Resolve();
您甚至可以更进一步,拥有MyObjectContext的多个命名实例,每个实例都使用自己的连接字符串连接到不同的数据库。

new ResolvedParameter(“MyConnectionString”),但出现错误,无法构造类型字符串。必须配置容器以提供此值,