英文:
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<IBackendComms, BackendComms>();
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);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论