使用.Net 6在控制台应用程序内托管Web API

myss37ts  于 2023-03-20  发布在  .NET
关注(0)|答案(1)|浏览(241)

我的问题很可能看起来有点琐碎,但我卡住了...
有很多关于如何在控制台应用程序中配置托管Web API的信息,但这不是我要找的。
我正在迁移旧的.NET Framework 4.8控制台应用程序,该应用程序作为Windows服务运行,并根据配置可以托管API端点,以访问内存中的信息,用于调试和监控目的。我正在将其迁移到.NET 6。
为了托管API,它使用Microsoft.AspNet.WebApi.SelfHost包中的HttpSelfHostServer类。在.NET 6中不再有这样的包。运行API的整个概念发生了变化,据我所知,根本没有这样的混合类型的应用程序。您可以构建控制台应用程序或Web API。
我遇到的问题是根据应用程序设置正确配置和运行API托管。它可以被禁用或启用。如果启用,API应该共享用于主服务应用程序的DI容器。
有没有人试图做这样的事情?任何想法或建议,在哪里寻找如何正确地做将不胜感激。

yi0zb3m4

yi0zb3m41#

我试了如下,这是你想要的:

Program.cs:

partial class Program
{
   
    static async Task Main(string[] args)
    {
        var configuration = new ConfigurationBuilder()
                            .SetBasePath(Directory.GetCurrentDirectory())
                            .AddJsonFile(path: "appsettings.json", optional: true, reloadOnChange: true)
                            .Build();
       
        var apienable = configuration.GetSection("Api").Value;
        Console.WriteLine(apienable);

      
        if (apienable == "enabled")
        {
            var builder = Microsoft.AspNetCore.Builder.WebApplication.CreateBuilder(new WebApplicationOptions() { ApplicationName = "ConsoleApp1", EnvironmentName = "Development" });
            builder.Host.ConfigureServices(
                services =>
                {
                    services.AddHostedService<Worker>();
                    services.RegistConsoleServices();
                    services.RegistWebapiServices();
                }
            );
            var app = builder.Build();

            // Configure the HTTP request pipeline.
            app.UseHttpsRedirection();

            app.UseAuthorization();

            app.MapControllers();

            await app.RunAsync();    

        }
        
        else
        {
            IHost host = Host.CreateDefaultBuilder(args)
            .ConfigureServices(services =>
              {
                  services.AddHostedService<Worker>();

              })
            .Build();

            await host.RunAsync();
        }
    }

}

服务:

public static class RegistService
{

    public static IServiceCollection RegistWebapiServices(this IServiceCollection services)
    {
        services.AddControllers();
        return services;
    }

    public static IServiceCollection RegistConsoleServices(this IServiceCollection services)
    {
        services.AddScoped<ISomeService,SomeService>();
        return services;
    }

}

public interface ISomeService
    {
        void Export();
    }
    public class SomeService : ISomeService
    {
        public void Export()
        {
            Console.WriteLine("HellowWord");
        }
    }

辅助进程(从默认Windows服务项目复制)

public class Worker : BackgroundService
    {
        private readonly ILogger<Worker> _logger;

        public Worker(ILogger<Worker> logger)
        {
            _logger = logger;
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
                await Task.Delay(1000, stoppingToken);
            }
        }
    }

控制器:从默认webapi项目中占用

[ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        private static readonly string[] Summaries = new[]
        {
        "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
    };

        private readonly ISomeService _service;

        public WeatherForecastController(ILogger<WeatherForecastController> logger, ISomeService service)
        {
            _service = service;
        }

        [HttpGet(Name = "GetWeatherForecast")]
        public IEnumerable<WeatherForecast> Get()
        {

            _service.Export();

            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = Random.Shared.Next(-20, 55),
                Summary = Summaries[Random.Shared.Next(Summaries.Length)]
            })
            .ToArray();
        }
    }

结果:

相关问题