【问题标题】:Is there a way to automatically resolve and start an autofac startable in module?有没有办法在模块中自动解析和启动可启动的 autofac?
【发布时间】:2015-08-27 09:25:21
【问题描述】:

我正在使用 autofac IStartables 来加载配置,例如

public class MyConfig : IMyConfig, IStartable
{
  public string configValue { get; private set; }

  public void Start()
  {
    configValue = ... // Load from config file
  }
}

然后在引导程序模块中,像这样注册它:

builder.RegisterType<MyConfig>().As<IMyConfig>().As<IStartable>().SingleInstance();

当使用 autofac 解析构造函数中的配置时,这一切都很好,但有时我想在引导程序模块本身中使用一些配置值。我已经设法通过使用:

var config = new MyConfig();
config.Start();
// now we can use config.configValue

但是,这 2 步初始化似乎不是很干净 - 有没有更好的方法来使用 autofac?

【问题讨论】:

  • 我不明白到底是什么问题。当您说“但有时我想在引导程序模块本身中使用一些配置值”时,您的意思是什么?
  • bootstrapper 模块中注册的实例需要根据配置值表现不同,所以我需要使用模块中的配置值。
  • 你能举一些你想要达到的目标的可靠例子吗(用一些代码)?
  • 在模块中使用配置不是问题,所以我没有包含该代码,手动调用 config.Start() 似乎不对,这是代码 sn-p在我的问题的底部。

标签: c# .net autofac ioc-container


【解决方案1】:

您无需致电Start()。构建容器时会自动调用它。这就是IStartable 的全部意义所在。

http://docs.autofac.org/en/latest/lifetime/startup.html

【讨论】:

  • 我不确定这是否会有所帮助,正如他们在您发布的链接上所说的那样:“第一次构建容器时将调用 Start [...]。”但是,我希望它可以在我的引导程序模块中使用,并且我认为 autofac 仅在从构造函数中使用它们时才构建容器。我需要重新审视它并创建一个示例应用程序,因为很明显我的描述不够清楚......
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-10-25
  • 2021-10-20
  • 2021-02-20
  • 2013-06-23
  • 1970-01-01
  • 2014-08-22
  • 2020-08-11
相关资源
最近更新 更多