kudlatiger
kudlatiger

Reputation: 3288

AppSettings not getting resolved via constructor injection

I have the configuration in appsettings.json as follows:

{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
  "Default": "Warning"
}
},
 "GatewaySettings": {
 "DBName": "StorageDb.sqlite",
 "DBSize": "100"    
 }
}   

Here is the class to represent the configuration data

 public class GatewaySettings
 {
    public string DBName { get; set; }
    public string DBSize { get; set; }
 }

Configured service as follows:

  services.AddSingleton(Configuration.GetSection("GatewaySettings").Get<GatewaySettings>());

but I'm getting this error:

Value cannot be null. Parameter name: implementationInstance'

Code:

  public class SqlRepository
  {
        private readonly GatewaySettings _myConfiguration;

        public SqlRepository(GatewaySettings settings)
        {
              _myConfiguration = settings;
        }
  }

Dependency injection code:

var settings = new IOTGatewaySettings();
builder.Register(c => new SqlRepository(settings))

Background

I am hosting ASPNET CORE application as windows service, and .NET Framework is 4.6.1

Note: similar question appears here but there is no solution provided.System.ArgumentNullException: Value cannot be null, Parameter name: implementationInstance

Upvotes: 3

Views: 2777

Answers (2)

Joe Audette
Joe Audette

Reputation: 36736

You should use IOptions of T

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

  public class SqlRepository
  {
    private readonly GatewaySettings _myConfiguration;
    public SqlRepository(IOptions<GatewaySettings> settingsAccessor)
    {
          _myConfiguration = settingsAccessor.Value;
    }
  }

you need these packages

<PackageReference Include="Microsoft.Extensions.Options" Version="2.1.0" />
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="2.1.0" />

Reference Options pattern in ASP.NET Core

Upvotes: 3

gunr2171
gunr2171

Reputation: 17579

Don't add concrete data model classes into DI - use the IOptions<> framework.

In your startup:

services.AddOptions();

// parses the config section into your data model
services.Configure<GatewaySettings>(Configuration.GetSection("GatewaySettings"));

Now, in your class:

public class SqlRepository
{
    private readonly GatewaySettings _myConfiguration;
    public SqlRepository(IOptions<GatewaySettings> gatewayOptions)
    {
        _myConfiguration = gatewayOptions.Value;
        // optional null check here
    }
}

Note: if your project does not include the Microsoft.AspNetCore.All package, you will need to add another package Microsoft.Extensions.Options.ConfigurationExtensions to get this functionality.

Upvotes: 9

Related Questions