为参数的具体名称注册字符串值

Tom*_*sup 4 c# ioc-container inversion-of-control autofac

我正在使用Autofac,我有几个类要求参数类型字符串和名称lang.有没有办法将字符串值注册到名为"lang"的所有参数,所以它会自动解决?我不想编辑任何构造函数,因为它不是我的代码(我知道接受例如CultureInfo会使注册变得容易..)

导致语法短的内容,如builder.Register(lang =>"en-US").As().Named("lang")

会是理想的.

谢谢.

Tra*_*lig 9

解决此问题的一种相当简单的方法是使用自定义Autofac模块.

首先,实现模块并处理IComponentRegistration.Preparing事件.这也是您存储参数值的位置:

using System;
using Autofac;
using Autofac.Core;

public class LangModule : Module:
{
  private string _lang;
  public LangModule(string lang)
  {
    this._lang = lang;
  }

  protected override void AttachToComponentRegistration(
    IComponentRegistry componentRegistry,
    IComponentRegistration registration)
  {
    // Any time a component is resolved, it goes through Preparing
    registration.Preparing += InjectLangParameter;
  }

  protected void InjectLangParameter(object sender, PreparingEventArgs e)
  {
    // Add your named parameter to the list of available parameters.
    e.Parameters = e.Parameters.Union(
      new[] { new NamedParameter("lang", this._lang) });
  }
}
Run Code Online (Sandbox Code Playgroud)

现在您已拥有自定义模块,您可以将其与其他依赖项一起注册,并提供您想要注入的值.

var builder = new ContainerBuilder();
builder.RegisterModule(new LangModule("my-language"));
builder.RegisterType<LangConsumer>();
...
var container = builder.Build();
Run Code Online (Sandbox Code Playgroud)

现在,当您解析具有字符串参数"lang"的任何类型时,您的模块将插入您提供的值.

如果需要更具体,可以使用事件处理程序中的PreparingEventArgs来确定要解析的类型(e.Component.Activator.LimitType)等等.然后您可以动态决定是否包含参数.