在Blazor WASM中注入自定义对象。

huangapple go评论79阅读模式
英文:

Injecting custom objects in Blazor WASM

问题

我想将与后端API通信的代码“委托”给一个单独的类,就像我注入HttpClient一样,我创建了一个单独的类并在Program.cs中进行了注册:

builder.Services.AddScoped<IBackendComms, BackendComms>();

然后我在组件中进行了注入:

@inject BackendComms backendComms

但是当我这样做时,启动项目后出现了“未处理的错误”。

我该如何正确在Razor文件中注入自定义类?

英文:

I want to "delegate" my code responsible for communications with the backend API to a separate class which I want to inject into my Blazor components just like I inject the HttpClient. I create the separate class and registere it in Program.cs:

builder.Services.AddScoped&lt;IBackendComms, BackendComms&gt;();

And I inject it in a component:

@inject BackendComms backendComms

But when I do this I get the "Unhandled error" after starting the project.

How do I properly inject my custom classes in razor files?

答案1

得分: 1

在你的剃刀组件中,注入接口而不是类:

@inject IBackendComms _backendComms

然后,你可以从组件的代码中调用接口具有的任何方法:

_backendComms.DoSomething(someParam);
英文:

In your razor component, inject the Interface instead of the class:

@inject IBackendComms _backendComms

Then you can call any method the interface has from your component's code:

_backendComms.DoSomething(someParam);

huangapple
  • 本文由 发表于 2023年6月30日 02:36:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/76583796.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定