注册字符串值作为参数的具体名称 [英] Register string value for concrete name of parameter

查看:86
本文介绍了注册字符串值作为参数的具体名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using Autofac and I have several classes which ask for parameter of type string and name lang. Is there a way to register a string value to all parameters named "lang", so it resolves automatically? I do not want to edit any of the constructors, since it is not my code (I know accepting e.g. CultureInfo would make registration easy..)

某种导致语法短的东西,例如 builder.Register(lang =>"en-US").As().Named("lang")

Something resulting in short syntax like builder.Register(lang => "en-US").As().Named("lang")

将是理想的.

谢谢.

推荐答案

一种非常简单的解决方法是使用自定义Autofac模块.

A fairly simple way to solve this is with a custom Autofac module.

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

First, implement the module and handle the IComponentRegistration.Preparing event. This is also where you'll store the value for your parameter:

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) });
  }
}

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

Now that you have your custom module, you can register it along with your other dependencies and provide the value you want injected.

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

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

Now when you resolve any type that has a string parameter "lang" your module will insert the value you provided.

如果需要更具体,则可以在事件处理程序中使用PreparingEventArgs确定要解析的类型(e.Component.Activator.LimitType)等事情,然后可以即时确定是否包括参数.

If you need to be more specific, you can use the PreparingEventArgs in the event handler to determine things like which type is being resolved (e.Component.Activator.LimitType), etc. Then you can decide on the fly whether to include your parameter.

这篇关于注册字符串值作为参数的具体名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆