taormania taormania - 5 months ago 30
ASP.NET (C#) Question

Adding loading configuration into inject dependencies in asp.net core

In my dotnetcore api I have some repository classes I'm injecting by using the services.AddTransient method in my Startup.cs


I'm also loading a section of my appsettings.json into a custom object also in the Startup.cs


My repository class needs to load the db connection string from the appsettings.json. Is there a way to inject these settings straight to the repository class? Or is it up to the constructor of the controller to pass the connection string to the repository class?


Yes, you can inject this directly to your repository.

    public MyRepository(IOptions<MyConfig> config)
        var connString = config.Value.DbConnString;

where MyConfig is a POCO object of your configuration and is getting added/registered in startup:

    public void ConfigureServices(IServiceCollection services)

The MyConfig can look something like this:

    public class MyConfig
        public string DbConnString { get; set; }

And the appsettings.json like this:

  "ApplicationName": "MyApp",
  "Version": "1.0.0",
  "DbConnString ": "my-conn-string"