Home > database >  How to asociate appsettings.json with a class and Dependency Injection?
How to asociate appsettings.json with a class and Dependency Injection?

Time:11-19

I have an API .NET 5 proyect and I have another proyect (library) that is reference from the API.

I have this appsettings.json in the API project:

 {
  "ConfigurationSettings": {
    "ConnectionStrings": {
      "DefaultConnection": "connStringDefault",
      "Other": "connStringOther"
    }
  }
}

And this class in the library:

public class ConfigurationSettings
{
    public ConnectionStrings ConnectionStrings { get; set; }
}

public class ConnectionStrings
{
    public string DefaultConnection { get; set; }

    public string Other { get; set; }
}

I want to use this class to search in the appsettings.json, like this:

string ConnString = ConfigurationSettings.ConnectionStrings.DefaultConnection;

But I need this to be with dependency injection, to use like this:

 private readonly IEmpleadoRepository _empleadoRepository;
    private readonly IMapper _mapper;
    private readonly IConfigurationSettings _config;


    public GetEmpleadoByIdHandler(IEmpleadoRepository empleadoRepository, IMapper mapper, IConfigurationSettings config)
    {
        _empleadoRepository = empleadoRepository;
        _mapper = mapper;
        _config = config;
    }

I google it and I cannot find the correct steps.

CodePudding user response:

you need several steps

add this line to your startup

services.Configure<ConnectionStrings>(configuration
        .GetSection("ConnectionStrings"));

inside of the repository you can use this way

private readonly IEmpleadoRepository _empleadoRepository;
    private readonly IMapper _mapper;
 private readonly ConnectionStrings _connectionStrings;

public GetEmpleadoByIdHandler(
IEmpleadoRepository empleadoRepository, 
IMapper mapper, 
IOptions<ConnectionStrings> connectionStrings)
 {
        _empleadoRepository = empleadoRepository;
        _mapper = mapper;

      _connectionStrings = new ConnectionStrings
        {
         DefaultConnection = connectionStrings.Value.DefaultConnection,
            Other=connectionStrings.Value.Other
        };
 }

CodePudding user response:

With this nuget:

(Microsoft.Extensions.Configuration.Abstractions)

and this other:

(Microsoft.Extensions.Configuration.Binder)

You can inject dependency like this:

    private readonly IConfiguration _config;


    public GetEmpleadoByIdHandler(IConfiguration config)
    {
        _config = config;
    }

then you can do this:

Configuration config = new Configuration();
            _config.Bind("ConfigurationSettings", config);

            string conn = config.ConnectionStrings.MongoDB;
  • Related