gpt4 book ai didi

c# - 通过 JSON 文件配置 ServiceCollection

转载 作者:行者123 更新时间:2023-11-30 15:54:32 25 4
gpt4 key购买 nike

是否有通过包含接口(interface) -> 类映射 的 JSON 文件在 .NET Core 2.0 中配置依赖项注入(inject)的示例?例如

var someServiceConfigBuilder = new ConfigurationBuilder();
someServiceConfigBuilder.AddJsonFile("someservice.json");
var someServiceConfig = someServiceConfigBuilder.Build();

var services = new ServiceCollection();
services.AddOptions();
services.Configure<SomeServiceOptions>(someServiceConfig);
services
// TODO this should really come from the JSON config file
.AddTransient<ISomeService, SomeService>();

因此,与其通过调用 AddTransient() 对映射进行硬编码,不如让此信息来自 JSON 文件。

这是否受支持?如果是,JSON 配置的预期格式是什么?

最佳答案

Replacing the default services container

The built-in services container is meant to serve the basic needs of the framework and most consumer applications built on it. However, developers can replace the built-in container with their preferred container. The ConfigureServices method typically returns void, but if its signature is changed to return IServiceProvider, a different container can be configured and returned. There are many IOC containers available for .NET.

(强调我的)

引用:Introduction to Dependency Injection in ASP.NET Core

因此,我建议检查是否已经有第 3 方 DI 框架提供该功能并具有可以与 .Net Core 集成的扩展。

Note

When using a third-party DI container, you must change ConfigureServices so that it returns IServiceProvider instead of void.

关于c# - 通过 JSON 文件配置 ServiceCollection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50319084/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com