如何将参数传递给Blazor服务



我有一个类似以下示例代码的服务:

using System.Collections.Generic;
using System.Threading.Tasks;
namespace BasicDependencyInjection
{
public interface IToDoApi
{
Task<IEnumerable<ToDo>> GetToDosAsync();
}
public class ToDoApi : IToDoApi
{
private readonly IEnumerable<ToDo> Data;
public ToDoApi()
{
Data = new ToDo[]
{
new ToDo { Id = 1, Title = "To do 1", Completed = true},
new ToDo { Id = 2, Title = "To do 2", Completed = false},
new ToDo { Id = 3, Title = "To do 3", Completed = false},
};
}
public Task<IEnumerable<ToDo>> GetToDosAsync() => Task.FromResult(Data);
}
}

这不是我的代码,只是教程页面上的一个示例代码

以下是该服务的注册方式。

service.AddSingeton<IToDoApi, ToDoApi>();

我的问题是,我需要将一个值传递给服务,即传递给ToDoApi()方法。

如何做到这一点?例如,我如何在不在代码中硬编码的情况下将令牌传递给服务。

还有一件事,我不能将param传递给register方法,每当我在组件中使用服务时,我都想传递param,因为提供服务的令牌来自组件。

感谢

您需要这样做:

public class ToDo
{
public int Id { get; set; }
public string Title { get; set; } = string.Empty;
public bool Completed { get; set; }
}
public interface IToDoApi
{
Task<IEnumerable<ToDo>> GetToDosAsync();
}
public class ToDoApi : IToDoApi
{
private readonly IEnumerable<ToDo> Data;
private bool initialized;

public ToDoApi()
{
Data = new ToDo[]
{
new ToDo { Id = 1, Title = "To do 1", Completed = true},
new ToDo { Id = 2, Title = "To do 2", Completed = false},
new ToDo { Id = 3, Title = "To do 3", Completed = false},
};
}
public void Initialize(bool initialize)
{
initialized = initialize;
}
public Task<IEnumerable<ToDo>> GetToDosAsync()
{
if (!initialized)
throw new Exception("You must initialize ToDoAPI before trying to use it");

return Task.FromResult(Data);
} 
}

您可以从获取数据的组件调用Initialize,并传入您想要的任何数据。我把它简单化了,只传入了实际的bool。

服务注册:

builder.Services.AddScoped<ToDoApi>();

这是一个演示页面:

@page "/"
@inject ToDoApi Service
<PageTitle>Index</PageTitle>
<h1>Hello, world!</h1>
Welcome to your new app.
<div class="p-2 m-2 ">
Records: @list.Count();
</div>
<div class="p-2 m-2 ">
<button class="btn btn-danger" @onclick="First">Unsafe</button>
<button class="btn btn-primary" @onclick="Second">Safe</button>
</div>
@code {
IEnumerable<ToDo> list = Enumerable.Empty<ToDo>();
private async Task First()
{
list = await Service.GetToDosAsync();
}
private async Task Second()
{
Service.Initialize(true);
list = await Service.GetToDosAsync();
}
}

相关内容

  • 没有找到相关文章