IOptions的.NET Core 3 Worker服务依赖项注入配置

编程入门 行业动态 更新时间:2024-10-10 16:20:00
本文介绍了IOptions的.NET Core 3 Worker服务依赖项注入配置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我对工人服务部的直接投资有疑问,下面回答了另一篇文章。

i have a question about DI on Worker Service that answered another post below.

。NET Core 3 Worker服务设置依赖项注入

如果我想添加一些帮助程序类并进行了如下注册。 如何使用该选项注入。 因为我想我错过了一些东西...

what if i want to add some helper class and registered as below. How can i use that option injection. because i think, i missed something...

public static IHostBuilder CreateHostBuilder(string[] args) { return Host.CreateDefaultBuilder(args) .ConfigureAppConfiguration((hostContext, config) => { // Configure the app here. config .SetBasePath(Environment.CurrentDirectory) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile($"appsettings.{hostContext.HostingEnvironment.EnvironmentName}.json", optional: true); config.AddEnvironmentVariables(); Configuration = config.Build(); }) .ConfigureServices((hostContext, services) => { services.AddOptions(); services.Configure<MySettings>(Configuration.GetSection("MySettings")); services.AddSingleton<RedisHelper>(); services.AddHostedService<Worker>(); }); }

RedisHelper类的构造函数为Worker。

RedisHelper class has a constructor like this as Worker.

public static MySettings _configuration { get; set; } public RedisHelper(IOptions<MySettings> configuration) { if (configuration != null) _configuration = configuration.Value; }

推荐答案

无需构建配置你自己您可以通过 hostContext

No need to build the config yourself. You can access it in the ConfigureServices via the hostContext

public static IHostBuilder CreateHostBuilder(string[] args) { return Host.CreateDefaultBuilder(args) .ConfigureAppConfiguration((hostContext, config) => { // Configure the app here. config .SetBasePath(Environment.CurrentDirectory) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile($"appsettings.{hostContext.HostingEnvironment.EnvironmentName}.json", optional: true); config.AddEnvironmentVariables(); }) .ConfigureServices((hostContext, services) => { services.AddOptions(); services.Configure<MySettings>(hostContext.Configuration.GetSection("MySettings")); services.AddSingleton<RedisHelper>(); services.AddHostedService<Worker>(); }); }

现在,只需将选项注入所需的帮助器类中

Now it is just a matter of injecting the options into the desired helper class

//... public RedisHelper(IOptions<MySettings> configuration) { if (configuration != null) _configuration = configuration.Value; } //...

服务

public Worker(RedisHelper helper) { this.helper = helper; }

更多推荐

IOptions的.NET Core 3 Worker服务依赖项注入配置

本文发布于:2023-11-06 01:58:28,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1562430.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:NET   IOptions   Worker   Core

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!