Reputation: 175
I have a very strange problem in my Blazor project. I am using Dependency Inject to user my "CompanyService" service. Here is how I am registering my service
// Servies Injection
services.AddSingleton<UserService, UserService>();
services.AddSingleton<CompanyService, CompanyService>();
And I am injecting that service in my razor component as
@inject CompanyService CompanyService
@inject NavigationManager NavigationManager
I need to pass these services to my ViewModel and I am doing like this (CompanesList is my Razor component name so it is constructor)
public CompaniesList()
{
Context = new CompaniesListVm(NavigationManager, CompanyService);
}
When I debug this code, I always get services as null (both NavigationManager, CompanyService). Here is my file position in my project
Can anyone please help me on this?
P.S I am also using MatBlazor for my UI.
Thank you
Regards J
Upvotes: 0
Views: 4872
Reputation: 175
The problem was:
I was initializing my VM in constructor, which is wrong
public CompaniesList()
{
Context = new CompaniesListVm(NavigationManager, CompanyService);
}
After changing to
protected override void OnInitialized()
{
Context = new CompaniesListVm(NavigationManager, CompanyService);
}
All works fine.
Regards
Upvotes: 5
Reputation: 45734
This is wrong:
services.AddSingleton<UserService, UserService>();
services.AddSingleton<CompanyService, CompanyService>();
It should be:
services.AddSingleton<IUserService, UserService>();
services.AddSingleton<ICompanyService, CompanyService>();
But if you did not define interfaces, then it should be:
services.AddSingleton<UserService>();
services.AddSingleton<CompanyService>();
Where do you do this
public CompaniesList()
{
Context = new CompaniesListVm(NavigationManager, CompanyService);
}
Show all your code...
In any case, use the @inject directive in the view portion (Razor markups) of your component, or define a property annotated with the Inject attribute, as for instance:
[Inject] Public NavigationManager NavigationManager { get; set; }
Hope this helps...
Upvotes: 4