Using Microsoft DependencyInjection, Configuration and Logging outside of an ASP.Net project

I wanted to use Microsoft’s dependency injection framework for a console application I was building, a little web scraper for fun. I thought it would be a simple way to get logging and configuration injection for free (using the libraries from ASP.Net). Its a bit overkill for the purpose of this application, but gave me a better idea of how ASP.Net core works under the hood.

The tricky part was finding which libraries I needed and knowing what functions to call to setup DI.

The main part of setting up Microsoft.Extensions.DependencyInjection is setting up the ServiceCollection. The service collection is how you define which services you want to register within the application, using more or less the same syntax as registering services with ASP.Net Core.

/// <summary>
/// Handles setting up the app using DI
/// 
/// This makes use of the following libraries:
/// - Microsoft.Extensions.DependencyInjection (For handling dependency injection)
/// - Microsoft.Extensions.Configuration (For handling configuration)
/// - Microsoft.Extensions.Configuration.Json (For parsing appsettings.json)
/// - Microsoft.Extensions.Logging (For logging)
/// - Microsoft.Extensions.Logging.Abstractions
/// - Microsoft.Extensions.Logging.Configuration
/// - Microsoft.Extensions.Logging.Console
/// 
/// This method sets up the configuration builder, which loads in the appsettings.json
/// (containing the configuration for the logging framework), then create the services
/// using DI
/// 
/// </summary>
/// <param name="url">The URL to start the web crawler at</param>
static void start(string url) {

    var configuration = new ConfigurationBuilder()
        .AddJsonFile("appsettings.json")
        .Build();

    var services = new ServiceCollection();
    services.AddSingleton<IConfiguration>(configuration);
    services.AddScoped<PageCrawler>();
    services.AddLogging(logger =>
    {
        logger.AddConfiguration();
        logger.AddConsole();
    });

    var serviceProvider = services.BuildServiceProvider();

    var crawler = serviceProvider.GetService<PageCrawler>();
    var page = crawler.Crawl(url);
    Console.WriteLine(page.ToString());
}

In the example above, we initialise the service provider and register some services:

  • The configuration service from Microsoft.Extensions.Configuration (e.g. appsettings.json)
  • The PageCrawler service, which is a simple class I wrote
  • The logging service from Microsoft.Extensions.Logging

After registering the services, we build the service provider. Now with the service provider we can get the services and all methods on them.

Again, this is a bit overkill for this simple example, but it shows how the library can be used outside of ASP.Net.