0
votes

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?

1
Have you tried it? - Aluan Haddad
I think that I am very close based on this: stackoverflow.com/questions/31453495/… - commodore73

1 Answers

0
votes

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.