Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 538
Moritz Rinckens Avatar asked Oct 27 '25 10:10

Moritz Rinckens


1 Answers

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
like image 176
Vencovsky Avatar answered Oct 29 '25 23:10

Vencovsky



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!