3

In my Asp.Net Core API, I have some repository classes I'm injecting by using the services.AddTransient method in my Startup.cs

services.AddTransient<IRepository, Repository>();

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

services.Configure<AppSettings>(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?

1
  • You can inject the config into your controller, then, pass it to your repository class. Commented Nov 23, 2016 at 18:28

1 Answer 1

2

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"
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I guess I just misunderstood that the configuration wouldn't just apply to the controllers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.