Search code examples
.netasp.net-core.net-6.0

Host Web API inside console app with .Net 6


My question most likely will look like a bit trivial but I'm stuck...

There is a lot of info about how to configure hosting Web API in a console app, but it's not what I'm looking for.

I'm in process of migrating old .NET Framework 4.8 console app that was running as a Windows service and depending on configuration can host API endpoints to get access to the in memory information for debugging and monitoring purposes. I'm migrating it to .NET 6.

In order to host the API it uses HttpSelfHostServer class from Microsoft.AspNet.WebApi.SelfHost package. There is no such package anymore in .NET 6. The whole concept running API is changed and so far as I can see there is no such a hybrid type of applications at all. You either build a console app or a Web API.

The problem that I have is properly configure and run API hosting depending on app settings. It either can be disabled or enabled. And if it's enabled API should share DI containers that used for the main service app.

Did someone tried to do anything like that? Any ideas or suggestion where to look how to do it properly would be much appreciated.


Solution

  • I tried as below,is it what you want:

    enter image description here

    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();
            }
        }
    
    }
    

    Services:

    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");
            }
        }
    

    Worker(Copied from a default windows service project)

    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);
                }
            }
        }
    

    Controller: conpied form a default webapi project

    [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();
            }
        }    
    

    Result:

    enter image description here

    enter image description here