0

I want to use the same code and hopefully configuration to set up DI for both ASP.NET core and .net core command-line tools.

I understand how to use Startup.cs to configure services for ASP.NET core. I understand how to build a ServiceCollection in a command-line tool, though other than accessing it explicitly, I am not exactly sure how to use it, and I think my CLT has to manage the service collection itself (unlike ASP.NET that provides a service collection and constructor injection).

Can my web and CLT projects use the same extension method to register my services? Startup.ConfigureServices would pass the ServiceCollection and Configuration that it receives to my extension method. The CLT I can pass the ServiceCollection that the CLT manages, but can it get the same type of Configuration from an appsettings.json file?

Ferran Buireu
  • 28,630
  • 6
  • 39
  • 67
commodore73
  • 61
  • 2
  • 11

1 Answers1

0

In the CLT I needed some nuggets:

Microsoft.Extensions.Cofiguration.Json
Microsoft.Extensions.DependencyInjection
Microsoft.Extensions.Hosting

private static ServiceCollection _services = new ServiceCollection();

    public static void Main(string[] args)
    {
        var builder = new ConfigurationBuilder()
//TODO:                .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
        builder.Build();
        IConfigurationBuilder configBuilder =
            new ConfigurationBuilder().AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
        ServiceProvider provider = ConfigureServices(_services, configBuilder.Build()).BuildServiceProvider(); //TODO: dispose
        _repo = provider.GetService<IRepository>();
        provider.Dispose();

I would probably set a property of the CLT to the provider, but then I am not sure how to ensure that it gets disposed.

commodore73
  • 61
  • 2
  • 11
  • It's definitely the right approach to use the app type agnostic configuration APIs as you are doing here. Regarding disposal: 1: Do not call dispose manually, it is not exception safe; use `using`, 2: your application's logical lifetime is entirely within the main method. Therefore using a field is pointless and confusing extra code. Remove the field and write `using var provider = new ConfigureServices(new ServiceCollection(), configBuilder.Build()).BuildServiceProvider();`. – Aluan Haddad May 22 '20 at 02:49