gpt4 book ai didi

c# - 自托管 .NET Core 控制台应用程序中的 Startup.cs

转载 作者:IT王子 更新时间:2023-10-29 03:57:23 27 4
gpt4 key购买 nike

我有一个自托管的 .NET Core 控制台应用程序

Web 显示了 ASP.NET Core 的示例,但我没有 Web 服务器。只是一个简单的命令行应用程序。

是否可以为控制台应用程序做这样的事情?

public static void Main(string[] args)
{
// I don't want a WebHostBuilder. Just a command line

var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.Build();

host.Run();
}

我想像在 ASP.NET Core 中一样使用 Startup.cs,但在控制台上。

我该怎么做?

最佳答案

所以我想到了这个解决方案,灵感来自公认的答案:

程序.cs

public class Program
{
public static void Main(string[] args)
{
IServiceCollection services = new ServiceCollection();
// Startup.cs finally :)
Startup startup = new Startup();
startup.ConfigureServices(services);
IServiceProvider serviceProvider = services.BuildServiceProvider();

//configure console logging
serviceProvider
.GetService<ILoggerFactory>()
.AddConsole(LogLevel.Debug);

var logger = serviceProvider.GetService<ILoggerFactory>()
.CreateLogger<Program>();

logger.LogDebug("Logger is working!");

// Get Service and call method
var service = serviceProvider.GetService<IMyService>();
service.MyServiceMethod();
}
}

启动.cs

public class Startup
{
IConfigurationRoot Configuration { get; }

public Startup()
{
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json");

Configuration = builder.Build();
}

public void ConfigureServices(IServiceCollection services)
{
services.AddLogging();
services.AddSingleton<IConfigurationRoot>(Configuration);
services.AddSingleton<IMyService, MyService>();
}
}

应用设置.json

{
"SomeConfigItem": {
"Token": "8201342s223u2uj328",
"BaseUrl": "http://localhost:5000"
}
}

我的服务.cs

public class MyService : IMyService
{
private readonly string _baseUrl;
private readonly string _token;
private readonly ILogger<MyService> _logger;

public MyService(ILoggerFactory loggerFactory, IConfigurationRoot config)
{
var baseUrl = config["SomeConfigItem:BaseUrl"];
var token = config["SomeConfigItem:Token"];

_baseUrl = baseUrl;
_token = token;
_logger = loggerFactory.CreateLogger<MyService>();
}

public async Task MyServiceMethod()
{
_logger.LogDebug(_baseUrl);
_logger.LogDebug(_token);
}
}

IMyService.cs

public interface IMyService
{
Task MyServiceMethod();
}

关于c# - 自托管 .NET Core 控制台应用程序中的 Startup.cs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41407221/

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