c# - 通过 JSON 文件配置 ServiceCollection

标签 c# .net dependency-injection .net-core

是否有通过包含接口(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/

相关文章:

c# - 应用程序 list 文件导致 Win 7 环境出现问题

c# - 在列上添加特定的自动过滤器

c# - 如何在 Visual Studio 2015 中禁用 namespace 缩写?

java - 通过方法创建对象时出现 Autowiring 问题

c# - .net 核心注册通用接口(interface)并使用 getservice 检索它们

C# - 我是否替换了完美的代码?

c# - Windows/.NET 自动更新框架功能集和安全性

c# - 使用 COM 组件时出错

.net - .NET 中自动生成的加密 key

未调用 WCF 自定义服务宿主工厂