Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 878
kudlatiger Avatar asked Feb 28 '26 01:02

kudlatiger


2 Answers

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.

like image 78
gunr2171 Avatar answered Mar 02 '26 14:03

gunr2171


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

like image 42
Joe Audette Avatar answered Mar 02 '26 16:03

Joe Audette



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!