没有注册的服务类型<ClassName>



我需要有2个组件之间的通信。我创建了一个类:

public interface IApplicationState
{
string PlateNumber { get; }
event Action OnPlateInput;
void SetPlateNumber(string plateNumber);
}
public class ApplicationState : IApplicationState
{
public string? PlateNumber { get; private set; }
public event Action OnPlateInput;
public void SetPlateNumber(string plateNumber)
{
PlateNumber = plateNumber;
NotifyPlateNumberChanged();
}
private void NotifyPlateNumberChanged() => OnPlateInput?.Invoke();
}

然后注册到我的Program.cs

builder.Services.AddScoped(sp => new HttpClient
{
BaseAddress = new Uri(builder.HostEnvironment.BaseAddress)
});
builder.Services.AddSingleton<IApplicationState, ApplicationState>();

然后在我的两个组件中调用它:

public partial class SideWidgetComponent : ComponentBase
{
[Inject] ApplicationState ApplicationState { get; set; }
private string _plateNUmber = string.Empty;
public async Task SetPlateNumber()
{
await Task.Run(() =>
{
if (_plateNUmber == string.Empty) return;
ApplicationState?.SetPlateNumber(_plateNUmber);
});
}
}
partial class PlateListComponent : ComponentBase
{
[Inject] private HttpClient? HttpClient { get; set; }
[Inject] private ApplicationState ApplicationState { get; set; }

protected override async Task OnInitializedAsync()
{
ApplicationState.OnPlateInput += ApplicationState_OnPlateInput;
}
}

当我启动程序时,我得到一个错误

不能在类型' alpr_web . client . pages . homecomponents . platelistcomponent '上为属性'ApplicationState'提供值。没有"alpr_web . shared . applicationstate"类型的注册服务。

您已经注册了接口IApplicationStateProgram.cs中,但正试图注入ApplicationState,即混凝土型。因为你没有注册具体类型,所以它不知道如何解析它。

因此,要么注册具体类型(即ApplicationState没有I),要么注入接口。两种方法都可以。

相关内容

  • 没有找到相关文章

最新更新