Autofac 注册时传参

可使用的参数类型

三种参数匹配机制:

  • NamedParameter 通过名字匹配目标参数 (常量)
  • TypedParameter 通过类型匹配目标参数(常量)
  • ResolvedParameter 复杂参数匹配
    假设你有个 configuration reader 需要传入一个 configuration section name
public class ConfigReader : IConfigReader
{
  public ConfigReader(string configSectionName)
  {
    // Store config section name
  }

  // ...read configuration based on the section name.
}

可以使用lambda表达式:

builder.Register(c => new ConfigReader("sectionName")).As<IConfigReader>();

或者在注册类型时传参(比较麻烦):

// Using a NAMED parameter:
builder.RegisterType<ConfigReader>()
       .As<IConfigReader>()
       .WithParameter("configSectionName", "sectionName");

// Using a TYPED parameter:
builder.RegisterType<ConfigReader>()
       .As<IConfigReader>()
       .WithParameter(new TypedParameter(typeof(string), "sectionName"));

// Using a RESOLVED parameter:
builder.RegisterType<ConfigReader>()
       .As<IConfigReader>()
       .WithParameter(
         new ResolvedParameter(
           (pi, ctx) => pi.ParameterType == typeof(string) && pi.Name == "configSectionName",
           (pi, ctx) => "sectionName"));

Lambda表达式在解析时传参:

在组件注册表达式中, 你可以用入参来改变你用于注册的委托签名. 并且不要只接受一个 IComponentContext 参数, 接受一个 IComponentContext 和一个 IEnumerable:

// Use TWO parameters to the registration delegate:
// c = The current IComponentContext to dynamically resolve dependencies
// p = An IEnumerable<Parameter> with the incoming parameter set
builder.Register((c, p) =>
                 new ConfigReader(p.Named<string>("configSectionName")))
       .As<IConfigReader>();

解析时传参:

var reader = scope.Resolve<IConfigReader>(new NamedParameter("configSectionName", "sectionName"));
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值