Code Monkey home page Code Monkey logo

consolebuildr's Introduction

ConsoleBuildR

Upgrade your console application and use the same pattern as .NET Core MVC projects to configure services, logging, and use application settings.

Installation

NuGet Package Manager

Install-Package ConsoleBuildR

.NET CLI

dotnet add package ConsoleBuildR

Usage

Add using statement to your application.

using ConsoleBuildR;

Start by implementing the IExcutable interface with the code you want to run.

public class MyProgram : IExecutable
{
    public Task Execute(string[] args)
    {
	    Console.WriteLine("Hello World!");
		
	    return Task.Delay(1000);
    }
}

Then, change your Program.cs file to look like this:

class Program
{
    static Task Main(string[] args) =>
        ConsoleBuilder.CreateDefaultBuilder()
        .Execute<MyProgram>()
        .Build()
        .Run(args);
}

The Execute<MyProgram>() method is how you tell the application builder what IExcutable implementations you want to run. You can chain multiple implementations to do different tasks.

Dependency Injection

Configuring implementations for dependency injection is simple using the ConfigureServices() method just like you can do in a .NET Core Web Application.

Here's how you would register an Entity Framework Core DbContext for your console application.

static Task Main(string[] args) =>
    ConsoleBuilder.CreateDefaultBuilder()
    .ConfigureServices((config, services) =>
    {
        services.AddDbContext<ApplicationDbContext>(options => options.UseInMemoryDatabase("ApplicationDb"));
    })
    .Execute<MyProgram>()
    .Build()
    .Run(args);

Now you can inject it into your IExcutable

public class MyProgram : IExecutable
{
	private readonly ApplicationDbContext _applicationDbContext;

	public MyProgram(ApplicationDbContext applicationDbContext)
	{
	    _applicationDbContext = applicationDbContext;
	}

	public Task Execute(string[] args)
	{
		// do something with your db
		return _applicationDbContext.SaveChangesAsync();
	}
}

Application Settings

Make sure the copy to output directory property on your appsettings.json is set to copy if newer or always.

Console Builder

ConsoleBuilder.CreateDefaultBuilder() will create a default implementation that has Microsoft's console logging, and use appsettings.json for configuration.

public static IConsoleBuilder CreateDefaultBuilder()
{
    var builder = new ConsoleBuilder()
        .ConfigureAppConfiguration((context, config) =>
        {
            var environmentName = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");

            config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                  .AddJsonFile($"appsettings.{environmentName}.json", optional: true, reloadOnChange: true);
        })
        .ConfigureLogging((context, logging) =>
        {
            logging.AddConfiguration(context.Configuration.GetSection("Logging"));
            logging.AddConsole();
        })
        .UseDefaultServiceProvider((context, options) =>
        {
            options.ValidateScopes = false;
        });

    return builder;
}

You can create your own configuration using the new ConsoleBuilder() if you require customizations.

Sample

class Program
{
    static Task Main(string[] args) =>
        ConsoleBuilder.CreateDefaultBuilder()
        .Execute<App>()
        .Build()
        .Run(args);
}

public class App : IExecutable
{
    private readonly ILogger _logger;
    private readonly IConfiguration _configuration;

    public App(ILogger<App> logger, IConfiguration configuration)
    {
        _logger = logger;
        _configuration = configuration;
    }

    public Task Execute(string[] args)
    {
        _logger.LogInformation(_configuration.GetValue<string>("Message"));

        return Task.Delay(100);
    }
}

appsettings.json

{
  "Message":  "Hello World!"
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.