i have a class that i can get the connaction string from the configuration
public class UserClass
{
private readonly IConfiguration _configuration;
public UserClass(IConfiguration configuration, ILogger<UserClass> logger) => _configuration = configuration;
public bool CheckUserPermissions(string email, string password, bool hashed, string SessionID)
{
string strConnString = _configuration.GetConnectionString("DefaultConnection").ToString();
}
}
in a static class i can't get the configuration.
public static class FunctionClass
{
public static DataTable GetData()
{
string strConnString = configuration.GetConnectionString("DefaultConnection").ToString();
}
}
You can't inject any service to the static classes. but if you need to access the connection string in a static class, You have two options:
1:
You can use ConfigurationBuilder
:
var config = new ConfigurationBuilder()
.AddJsonFile(dir) // dir: path to the configuration file
.Build();
var conStr = config.GetConnectionString("DefaultConnection");
2:
If it is an Asp.net core project, try to read the connection string in the startup class and set your connection string to a static
global property/field.
public static class FunctionClass
{
public static string ConnectionString = "";
// set the ConnectionString value in the startup
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.