如何用PARAMETER构造函数registerType?

Mar*_*tin 30 dependency-injection ioc-container unity-container

如何使用类型没有NO PARAMETER构造函数的容器注册类型.

实际上我的构造函数接受一个字符串,我通常传入一个表示Path的字符串.

所以当我解决它时会自动创建新类型但是传入一个字符串?

Chr*_*res 57

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

在API中,您可以:

container.RegisterType<MyType>(new InjectionConstructor("My string here"));
Run Code Online (Sandbox Code Playgroud)

这将选择一个带有单个字符串的构造函数,并在解析时将传递字符串"My string here".

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

<register type="MyType">
  <constructor>
    <param name="whateverParameterNameIs" value="My string here" />
  </constructor>
</register>
Run Code Online (Sandbox Code Playgroud)


小智 16

您还可以使用内置的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>();
Run Code Online (Sandbox Code Playgroud)

您甚至可以更进一步,并拥有多个MyObjectContext的命名实例,每个实例都使用自己的连接字符串连接到不同的数据库.