taormania taormania - 10 days ago 4
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

services.AddTransient();

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

services.Configure(Configuration.GetSection("AppSettings"));

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?

Answer

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)
    {
        ...
        services.Configure<MyConfig>(Configuration);
    }

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"
}
Comments