Reputation: 286
IConfiguration is always null no matter what i try.. I have also tried to add singleton to the startup class, but always null...
Startup class
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
Here is my Security class
IConfiguration _configuration { get;} **<<always null**
public Security(IConfiguration configuration) **<<always null**
{
_configuration = configuration;
}
public string GetConnectionString()
{
string connectionString = _configuration.GetConnectionString("localDb");
return connectionString;
}
Here is my Index.Razor page
namespace WebbiSkoolsQuizManager.Pages
{
public class IndexBase : ComponentBase
{
public IConfiguration Configuration { get; }
public async Task TryLogin(string user, string pass)
{
}
public async Task AddUserHash(string username, string password)
{
Security secure = new Security(Configuration);
string connectionstring = secure.GetConnectionString();
}
}
}
Appsettings.json
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"ConnectionKeys": {
"localDb": "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=Quiz;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"
},
"AllowedHosts": "*"
}
Thank you in advance, i have searched high and low, regarding a fix for blazor specific but i cant find anything.. (P.S its .Net core 3)
Upvotes: 3
Views: 1598
Reputation: 45704
I guess this: public IConfiguration Configuration { get; }
Should be:
[Inject]
public IConfiguration Configuration { get; }
Note: You can't simply define a property of a service, and expect it to be populated... If you're using a Razor component class definition (.cs) as in your case, you can inject the service by using the [Inject]
attribute. If you're using a Razor component (.razor), you can either use the @inject
directive at the view portion of the component, as for instance:
@page "/"
@inject IConfiguration Configuration
or in the @code
section, like this:
@code
{
[Inject]
public IConfiguration Configuration { get; }
}
Note also that if you want to inject a service into a normal C# class, you'll need to use constructor injection
Upvotes: 6