简体   繁体   中英

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?

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")));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM