0
votes

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

enter image description here

Can anyone please help me on this?

P.S I am also using MatBlazor for my UI.

Thank you

Regards J

2
You should inject CompaniesListVm instead IMO. avoid new as possibleagua from mars

2 Answers

3
votes

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...

1
votes

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