Moritz Rinckens
Moritz Rinckens

Reputation: 135

Inject Services into partional razor componet class

I want to split code in razor components. Html markup and logic. I am really new C#. When I try it like this

TaskManagement.razor.cs:

using Microsoft.AspNetCore.Components;
using System.Threading.Tasks;
using MintWebApp.Services;
using MintDataService;

namespace WebApp.Pages 
{
    partial class TaskManagement 
    {
        public TaskService _taskService;

        public TaskManagement(TaskService taskService)
        {
            _taskService = taskService;
        }

        protected override async Task OnInitializedAsync()
        {
            MintTaskFromJson task = await _taskService.GetExampleTask();
        }
    }
}

I get this error

MissingMethodException: No parameterless constructor defined for type 
'WebApp.Pages.TaskManagement'.

Which is the best way to inject services into the partinal class without inject the service in the razor file

Upvotes: 4

Views: 4439

Answers (1)

Vencovsky
Vencovsky

Reputation: 31713

You should use the Inject attribute

[Inject]
public TaskService TaskService { get; set; }

And don't forget to add dependency injection to your service

public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton<TaskService, TaskService>();
}

You can take a look at the docs that explains it.

Also found a tutorial that explains it.

Edit:

You should also notice that you can also inject it in the .razor file

@inject TaskService TaskService

Upvotes: 13

Related Questions