c# - 使用 Net Core 默认 DI 注入字符串和服务
问题描述
我有一个 Net Core 2.1 控制台应用程序,我在其中执行以下操作:
class Program
{
static void Main(string[] args)
{
var configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", false)
.Build();
var fullPath = configuration.GetValue<string>("tempPath:fullPath");
serviceCollection.AddTransient<MyService>();
serviceCollection.AddTransient<Worker>();
...
public class Worker
{
public string FullPath {get; set;}
private readonly MyService _myService;
public Worker(MyService myService,
string fullpath)
{
_myService = myService;
FullPath=fullpath;
}
换句话说,我需要以Worker
某种方式在我的类中注入服务和配置字符串。
有人可以建议我正确的方法吗?
解决方案
只需将您的 DI 配置更改为以下内容:
var fullPath = configuration.GetValue<string>("tempPath:fullPath");
serviceCollection.AddTransient<MyService>();
serviceCollection.AddTransient<Worker>(x => new Worker(x.GetRequiredService<MyService>(), fullPath));
或者按照建议使用IOptions
接口将您的配置对象注入到类中。
推荐阅读
- gradle - 为什么在 buildSrc 目录中的自定义 gradle.kts 文件中找不到“发布”功能?
- asp.net - .NET CORE 2.1.1 with Entity Framework Core 2.1.4 Code First:从字符串转换日期和/或时间时转换失败
- javascript - 异步函数返回未定义
- tsql - 将 Varchar() 转换为日期?
- hibernate - 如何使用带有参数化 Order By 子句的 JPA 查询
- mysql - 将两列与 where、group 和 have 相加
- sql - 在条件语句中使用 Replace 函数
- kubernetes - Spring Cloud Kubernetes:什么是集群读取器权限?
- swift - SpriteKit - 如何使用计时器过渡到新场景
- angular - 在角度 6 中绑定多个 for 循环内的值