Search code examples
c#.netasp.net-corecode-injection

Injection in a referenced class library?


I have a ASP.NET Core 2.1 website that references a class library(DAL). To access the connectionstring from the appsettings.json(ASP.NET project) I need inject the configuration somehow. I have created a class in the class Library that looks like this :

    public class Helper
{
    IConfiguration Configuration;
    public Helper(IConfiguration configuration)
    {
        Configuration = configuration;
    }
    public string GetConnectionString(string name)
    {
        return Configuration.GetConnectionString("DefaultConnection");
    }
}

The injection pattern do however not pick this up so it demands a IConfigration to create the class.

How do I access the appsettings.json from the class library?


Solution

  • Your class library should not know or care how you're handling configuration in your app. All your Helper class needs is a connection string, so that is what you should inject into it. How that string is provided is an implementation detail that's part of your application domain.

    public class Helper
    {
         public Helper(string connectionString)
         {
              // do something with connectionString
         }
    }
    

    Then, in your app:

    services.AddScoped(p =>
        new Helper(Configuration.GetConnectionString("DefaultConnection")));