0

My Web API is using other project for one controller. Service works fine. But I am struggling to inject connection string from main Web API project into controller in external project.

How could this be achieved?

public class MyExternalController : Controller
{
    private string _connStr;

    public MyExternalController(string connStr)
    {
        _connStr = connStr;
    }


    // actions here
}
3
  • Why are you injecting the connection string in the first place? You shouldn't use injected dependencies to build dependencies inline, you should inject the service configured already Commented Jun 1, 2018 at 16:16
  • 1
    You can only inject Services that have been registered. You should be injecting a DbContext instead. Commented Jun 1, 2018 at 16:20
  • 1
    Reference Options pattern in ASP.NET Core Commented Jun 1, 2018 at 16:27

1 Answer 1

3

As others said in the comments, for something like a controller, you should be injecting something concrete like a DbContext, not a connection string. However, for future reference your issue here is injecting a string. There's no way to register something in the DI container to satisfy a dependency like that. Instead, you should inject your configuration or a strongly-typed configuration class.

Injecting IConfigurationRoot is a bit of an anti-pattern, but for something like a connection string, it's fine:

public MyExternalController(IConfigurationRoot config)
{
    _connStr = config.GetConnectionString("MyConnectionString");
}

For everything else, though, you should use strongly-typed configuration classes.

public class FooConfig
{
    public string Bar { get; set; }
}

Then, in ConfigureServices:

services.Configure<FooConfig>(Configuration.GetSection("Foo"));

Which of course would correspond with some bit of config like:

{
    "Foo": {
        "Bar": "Baz"
    }
}

Then, in your controller, for example:

public MyExternalController(IOptionsSnapshot<FooConfig> fooConfig)
{
    _fooConfig = fooConfig.Value;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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