.NET 2.0 Console App - Reading app settings

514 views Asked by At

I am trying to get a .NET console application (Core 2.0) to read from an appsetting.json file. I have a webapi project that works fine with the following:

services.Configure<WebAppSettings>(Configuration.GetSection("WebAppSettings"));

But in the console app it says:

'ServiceCollection' does not contain a definition for 'Configure' and no extension method 'Configure' accepting a first argument of type 'ServiceCollection' could be found (are you missing a using directive or an assembly reference?)

I have the following packages installed in the console app project:

<PackageReference Include="Microsoft.Extensions.Configuration" Version="2.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="2.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="2.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="2.0.0" />

Here is the full Program.cs class:

using System;
using System.IO;
using Cam.Checker.Services;
using Cam.Common;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace Cam.Checker
{
    class Program
    {
        public static IConfigurationRoot Configuration { get; set; }
        static void Main(string[] args)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json");
                //.AddJsonFile($"appsettings.{env.EnvironmentName}.json", true, true);

            Configuration = builder.Build();

            var services = new ServiceCollection();
            services.AddTransient<ICheckerService, CheckerService>();
            // app settings
            services.Configure<WebAppSettings>(Configuration.GetSection("WebAppSettings"));
            var provider = services.BuildServiceProvider();

        }

}
}

Thank you!

1

There are 1 answers

1
kloarubeek On BEST ANSWER

You need to add the NuGet package Microsoft.Extensions.Options.ConfigurationExtensions to get the Configure extension method.