ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

CodeGo.net>通过JSON文件配置ServiceCollection

2019-11-09 02:05:17  阅读:11  来源: 互联网

标签:net-core dependency-injection c net



有没有一个示例,它通过一个包含接口->的JSON文件在.NET Core 2.0中配置依赖项注入.类映射?例如.

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

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

Note

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



标签:net-core,dependency-injection,c,net

专注分享技术,共同学习,共同进步。侵权联系[admin#icode9.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有