[英]Configuring services for ASP.NET core and .NET core CLT
I want to use the same code and hopefully configuration to set up DI for both ASP.NET core and .net core command-line tools.我想使用相同的代码并希望配置为 ASP.NET 内核和 .net 内核命令行工具设置 DI。
I understand how to use Startup.cs to configure services for ASP.NET core.我了解如何使用 Startup.cs 为 ASP.NET 内核配置服务。 I understand how to build a
ServiceCollection
in a command-line tool, though other than accessing it explicitly, I am not exactly sure how to use it, and I think my CLT has to manage the service collection itself (unlike ASP.NET that provides a service collection and constructor injection).我了解如何在命令行工具中构建
ServiceCollection
,尽管除了显式访问它之外,我不确定如何使用它,而且我认为我的 CLT 必须自己管理服务集合(与提供服务的 ASP.NET 不同集合和构造函数注入)。
Can my web and CLT projects use the same extension method to register my services?我的 web 和 CLT 项目可以使用相同的扩展方法来注册我的服务吗?
Startup.ConfigureServices
would pass the ServiceCollection
and Configuration that it receives to my extension method. Startup.ConfigureServices
会将它收到的ServiceCollection
和 Configuration 传递给我的扩展方法。 The CLT I can pass the ServiceCollection
that the CLT manages, but can it get the same type of Configuration from an appsettings.json
file? CLT 我可以传递 CLT 管理的
ServiceCollection
,但它可以从appsettings.json
文件中获得相同类型的配置吗?
In the CLT I needed some nuggets:在 CLT 中,我需要一些掘金:
Microsoft.Extensions.Cofiguration.Json
Microsoft.Extensions.DependencyInjection
Microsoft.Extensions.Hosting
private static ServiceCollection _services = new ServiceCollection();
public static void Main(string[] args)
{
var builder = new ConfigurationBuilder()
//TODO: .SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
builder.Build();
IConfigurationBuilder configBuilder =
new ConfigurationBuilder().AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
ServiceProvider provider = ConfigureServices(_services, configBuilder.Build()).BuildServiceProvider(); //TODO: dispose
_repo = provider.GetService<IRepository>();
provider.Dispose();
I would probably set a property of the CLT to the provider, but then I am not sure how to ensure that it gets disposed.我可能会将 CLT 的一个属性设置为提供者,但是我不确定如何确保它被处置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.