Halvard
Halvard

Reputation: 4001

How do I read .Net Core configuration in a standard class library?

Today (Nov 11th 2016) I downloaded the new Visual Studio 2017 RC, installed .Net Core 1.1 and set up a Web Api project (ASP.NET Core Web Application (.NET Core)). I then followed the instructions on how to read app settings from a config file. This worked fine.

Then I created a new project in the same solution. This was a Class Library (.NET Standard) under the .NET Core section. I added a class with an interface and set it up with default dependency injection.

Finally, I tried to use the configuration in the class library through constructor injection. I get this error message:

The type or namespace name 'IOptions<>' could not be found

Here is my class in the class library:

public class Firebase : IDatabase
{
    public Firebase(IOptions<AppSettings> appSettings)
    {
        //string basePath = 
    }
}  

Here is the ConfigureServices method in Startup.cs:

public void ConfigureServices(IServiceCollection services)
    {
        // Add framework services.
        services.AddMvc();
        services.AddTransient<IDatabase, Firebase>();

        // Set up configuration files.
        services.AddOptions();
        services.Configure<AppSettings>(options => Configuration.GetSection("AppSettings").Bind(options));
    }  

I tried to add

using Microsoft.Extensions.Options;  

to make it compile, but the light bulb is telling me that this is an unnecessary reference.

What am I missing? Is this not possible? Is there a special class library for .NET Core?

Upvotes: 2

Views: 4254

Answers (1)

Martijn van Put
Martijn van Put

Reputation: 3313

Working with IOptions{T} is the correct way in .NET Core. Visual Studio 2017 indicates there are unnecessary usings. This is a little bit confusing because Visual Studio indicates this when the pointer is on the Microsoft.Extensions.Options using. Looking to the proposal Visual Studio makes, it doesn't remove the Microsoft.Extensions.Options using but other usings for e.q. `System.

Upvotes: 7

Related Questions