如何配置Unity在RegisterType()期间为构造函数参数应用"常量"字符串?

Dav*_*nde 5 .net dependency-injection unity-container

这就是我的服务构造器的样子:

public Service(string path)
Run Code Online (Sandbox Code Playgroud)

我正在配置像这样的团结:

IUnityContainer container = new UnityContainer();
container.RegisterType<IService, Service>();
Run Code Online (Sandbox Code Playgroud)

这当然是不正确的.需要指定path参数,我希望可以从AppSettings配置它,所以在这种情况下我可以在配置期间设置它.

我该怎么做呢?

Mar*_*ann 8

据我所知,您希望从AppSetting中读取路径,然后以编程方式配置UnityContainer.

这可以这样做:

// Get path from app.config via ConfigurationManager.AppSettings

var container = new UnityContainer();
container.RegisterType<IService, Service>(new InjectionConstructor(path));
Run Code Online (Sandbox Code Playgroud)

  • 如果某人不清楚`ResolvedParameter <T>`,则必须将其传递给injectionConstructor:`container.RegisterType <IService,Service>(new InjectionConstructor(new ResolvedParameter <T>(),path));` (4认同)
  • 正是我需要的.作为后续,如果我有两个参数,一个可以使用RegisterInstance解析,以及此路径参数怎么办? (2认同)
  • 在这种情况下,您应该能够使用`ResolvedParameter <T>`. (2认同)