如何在.NET Core DI 中强制创建类实例?

Rob*_*III 8 c# dependency-injection asp.net-core

我有以下代码:

public void ConfigureServices(IServiceCollection services)
{
   services.AddOptions();

   services.Configure<MyConfig>(Configuration.GetSection("MySection"));
   services.AddSingleton<IMyClass>(sp => new MyClass(sp.GetService<IOptions<MyConfig>>()));
}
Run Code Online (Sandbox Code Playgroud)

这注册了一个单例MyClass,现在我可以让我的控制器采用类型为 的构造函数参数IMyClass。这按预期工作。

MyClass仅当控制器需要 时,才会首先实例化IMyClass。但是,我希望在任何人要求它之前MyClass就被实例化(因为它在它的构造函数中做了一些工作,需要一些时间)。

我可以做类似的事情:

public void ConfigureServices(IServiceCollection services)
{
   services.AddOptions();

   services.Configure<MyConfig>(configuration.GetSection("MySection"));

   var myinstance = new MyClass(/*...*/);  // How do I get MyConfig in here?
   services.AddSingleton<IMyClass>(myinstance);
}
Run Code Online (Sandbox Code Playgroud)

...但是我无法访问配置,因为我没有对IServiceProvidersp第一个代码示例中的变量)的引用。我如何到达服务提供者或者我必须做什么才能确保实例尽快初始化?

Nko*_*osi 4

在这种情况下,确实不需要,因为IOptions<T>您可以提取配置并将其直接传递给您的类,但如果您坚持使用选项,则可以使用OptionsWrapper<TOptions> Class

IOptions返回选项实例的包装器。

并将其传递给您的实例

// How do I get MyConfig in here?
MyConfig myConfig = configuration.GetSection("MySection").Get<MyConfig>();    
var wrapper = new OptionsWrapper<MyConfig>(myConfig);
var myinstance = new MyClass(wrapper);  
services.AddSingleton<IMyClass>(myinstance);
Run Code Online (Sandbox Code Playgroud)

从包装器的配置中提取您的设置。

ASP.NET Core 中的参考配置:绑定到对象图