Startup.cs in a self-hosted .NET Core Console Appl

2019-03-08 01:00发布

I have a self-hosted .NET Core Console Application.

The web shows examples for ASP.NET Core but i do not have a webserver. Just a simple command line application.

Is it possible to do something like this for console applications?

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

I would like to use a Startup.cs like in ASP.NET Core but on console.

How to this?

4条回答
何必那么认真
2楼-- · 2019-03-08 01:13

Yes, it is. ASP.NET Core applications can either be self-hosted - as in your example - or hosted inside a web server such as IIS. In .NET Core all apps are console apps.

查看更多
Evening l夕情丶
3楼-- · 2019-03-08 01:25

All .NET Core applications are composed of well-crafted independent libraries and packages which you're free to reference and use in any type of application. It just so happens that an Asp.net core application comes preconfigured to reference a lot of those libraries and exposes an http endpoint.

But if it's Dependency Injection you need for your console app, simply reference the appropriate library. Here's a guide: http://andrewlock.net/using-dependency-injection-in-a-net-core-console-application/

查看更多
Rolldiameter
4楼-- · 2019-03-08 01:26

Another way would be using HostBuilder from Microsoft.Extensions.Hosting package.

public static async Task Main(string[] args)
{
    var builder = new HostBuilder()
        .ConfigureAppConfiguration((hostingContext, config) =>
        {
            config.SetBasePath(Directory.GetCurrentDirectory());
            config.AddJsonFile("appsettings.json", true);
            if (args != null) config.AddCommandLine(args);
        })
        .ConfigureServices((hostingContext, services) =>
        {
            services.AddHostedService<MyHostedService>();
        })
        .ConfigureLogging((hostingContext, logging) =>
        {
            logging.AddConfiguration(hostingContext.Configuration);
            logging.AddConsole();
        });

    await builder.RunConsoleAsync();
}
查看更多
Bombasti
5楼-- · 2019-03-08 01:29

So i came across with this solution, inspired by the accepted answer:

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

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

appsettings.json

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

MyService.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();
}
查看更多
登录 后发表回答