Ingmar
Ingmar

Reputation: 1457

.NET Core 2.0 console application does not compile

I want to configure a .NET Core 2.0 CONSOLE application. There is one line that won't compile (see my note in the code).

I have checked so many blogs, websites, etc. This seems to be an approved way of configuring a .NET Core application. Am I missing an assembly reference?

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using System;
using System.IO;

namespace fbs.Console
{
    class Program
    {
        public static IConfiguration configuration;
        public static IServiceProvider serviceProvider;

        static void Main(string[] args)
        {
            // Create service collection
            ConfigureServices();

            var dbService = serviceProvider.GetRequiredService<IDbContext>();
        }

        private static void ConfigureServices()
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);

            configuration = builder.Build();

            var appSettings = new AppSettings();
            var section = configuration.GetSection("AppSettings");

            IServiceCollection services = new ServiceCollection();

            services.AddOptions();
            // The following statement does NOT compile???
            services.Configure<AppSettings>(section); 
            services.AddSingleton<IDbContext, DbContext>();

            serviceProvider = services.BuildServiceProvider();
        }
    }

    public class AppSettings
    {
        public string Database { get; set; }
    }

    public interface IDbContext
    {
        string Database { get; set; }
    }

    public class DbContext : IDbContext
    {
        public string Database { get; set; }

        public DbContext(IOptions<AppSettings> appSettings)
        {
            this.Database = appSettings.Value.Database;
        }
    }
}

Edit: The compiler error says:

Error CS1503    Argument 2: cannot convert from 'Microsoft.Extensions.Configuration.IConfigurationSection' to 'System.Action<fbs.Console.AppSettings'.

In order to replicate the problem, just create a new .NET Core 2.0 console application, copy&paste my code and try to compile.

Upvotes: 1

Views: 731

Answers (1)

Ingmar
Ingmar

Reputation: 1457

Solved: Indeed I have been missing to add Microsoft.Extensions.Options.ConfigurationExtensions to the project. I wasn't aware that this assembly is necessary because there seems to be no need to add it as "using" clause. At least, my code is now compiling by just adding the package with NuGet (but no changes to the using statements). I am a bit confused.

Upvotes: 2

Related Questions