使用“WithParameters”Autofac 注入失败

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

我正在尝试注册我创建的一些端点,但是,Autofac 抛出异常,说我尚未注册我的

BControl
类。这是我的注册码:

    builder.RegisterType<GControlEndpoint>().As<IBusConsumer>().SingleInstance();
    builder.RegisterType<BControlEndpoint>().As<IBusConsumer>().SingleInstance();

    builder.RegisterType<BSControlEndpoint>().As<IBusConsumer>().SingleInstance()
      .WithParameter((pi, c) => pi.Name == "bControlEndpoint",
        (pi, c) => c.Resolve<BControlEndpoint>())
      .WithParameter((pi, c) => pi.Name == "gControlEndpoint",
        (pi, c) => c.Resolve<GControlEndpoint>());

我的

BSControlEndpoint
代码如下:

  private BControlEndpoint bControlEndpoint;
  private GControlEndpoint gControlEndpoint;

  public BSControlEndpoint(
    BControlEndpoint bControlEndpoint,
    GControlEndpoint gControlEndpoint)
  {
    this.bControlEndpoint = bControlEndpoint;
    this.gControlEndpoint = gControlEndpoint;
  }

如有任何帮助,我们将不胜感激。

Autofac 错误是:

Autofac.Core.Registration.ComponentNotRegisteredException: The requested service 'Sa.BControlEndpoint' has not been registered. To avoid this exception, either register a component to provide the service, check for service registration using IsRegistered(), or use the ResolveOptional() method to resolve an optional dependency.

c# autofac
1个回答
1
投票

尝试将

AsSelf
添加到依赖项的注册定义中:

builder.RegisterType<GControlEndpoint>()
   .As<IBusConsumer>()
   .AsSelf()
   .SingleInstance();

builder.RegisterType<BControlEndpoint>()
    .As<IBusConsumer>()
    .AsSelf()
    .SingleInstance();

这也应该使

WithParameter
不再需要调用。

另一个选择是研究键控依赖项注册(docs

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