如何使用 PARAMETER 构造函数注册类型?

问题描述 投票:0回答:3

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

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

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

dependency-injection unity-container ioc-container
3个回答
63
投票

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

在 API 中,您可以:

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

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

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

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

19
投票

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

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


0
投票

13 年过去了,我仍在寻找同一问题的答案。

我从 UnityContainer.org 的 quickstart 文档中发现了如何做到这一点。

所有旧的答案都提供了一个使用

InjectionConstructor

 的解决方案,但在 2024 年我没有找到这个。

就像OP一样

就像OP一样,我有一个类需要作为字符串传入的Path来构造它。

我会保持我的样本很小。这是界面:

public interface ITrackable { // StorageTarget is one of the following: // 1. full-filename (including path) // 2. DB Connection string // 3. URI to location where data will be posted. String StorageTarget { get; } bool WriteActivity(String message); }
这是实现类的最小片段:

public class FileActivityTracker : ITrackable { private String FileName; public FileActivityTracker(String fileName) { FileName = fileName; } public string StorageTarget { get { return FileName; } } ...

注册并解决

我需要使用 Unity

Register

 我的类型,然后让它构建一个(通过 
Resolve
)。

代码

构建没有任何问题。 一旦代码ranRegister

方法就成功了,没有任何问题。
但是,当代码调用 
Resolve
 时,应用程序将崩溃,并显示以下内容:

有点令人困惑的错误

{"依赖解析失败,type = "FileActivityTracker", 名称=“(无)”。 while 时发生异常: while 解决。 例外是:InvalidOperationException -

类型 无法构造字符串。您必须将容器配置为 供应这个 值。 ----------------------------------------------------------- 在 异常发生时,容器为: 解决 文件活动跟踪器,(无) 解析参数“config” 构造函数 文件活动跟踪器( 解决(无) 解析参数 构造函数的“fileNameFileActivityTracker(System.String 文件名) 解析 System.String,(无) “}

解决方案

UnityContainer.org 上的文档显示了一个示例,并指出您需要注册将传递到构造函数中的字符串实例。

我只是在调用

Resolve

 方法之前添加了该调用,现在它可以正常工作(第一行,如以下示例所示)。

// Register string instance container.RegisterInstance(@"c:\user\user.name\myfile.log"); container.Resolve<FileActivityTracker();
顺便说一句,当调用 

Resolve

 方法时,您可以单步执行代码,并且可以看到正在执行的构造函数代码。

© www.soinside.com 2019 - 2024. All rights reserved.