ASP.NET Core – local debug console with DI

When Developing ASP.NET Core application, sometimes we want to debug some function which is not a controller method, for example, some services, but those services are using dependency injection. So even if we create a console application, and want to just “new” a service, there is lots of dependency parameters, and dependency inside those parameters.

Is there is way to auto wired dependency instance just like the ASP.NET Core application? Yes. We can create a console application, which is exactly ASP.NET Core application, but without MVC and let the application start a service method as a debug entry point.

1 Add DebugService.cs and in constructor you can inject whatever service you want:

public class DebugService
{
    private readonly ILogger _logger;
    private readonly IConfiguration _configuration;

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

2 Add a Start method as a debug entry point:

public class DebugService
{
    private readonly ILogger _logger;
    private readonly IConfiguration _configuration;

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

    public void Start()
    {
        Console.WriteLine("Start debug...");

        // debug code

        Console.ReadLine();
    }
}

3 Modify ConfigureServices method in Startup.cs file:

public void ConfigureServices(IServiceCollection services)
{
    ......
    services.AddScoped<DebugService>();
}

4 Modify Configure method in Startup.cs file:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider serviceProvider)
{
    ......
    serviceProvider.GetService<DebugService>().Start();
}

Now start application and you can debug your code in DebugService with DI you need.

Leave a comment