我如何在blazor组件类中为我自己的服务使用依赖注入?
组件类:
[Inject]
public HttpContentFormatter IHttpContentFormatter {
get;
set;
}发布于 2019-07-23 19:18:46
假设您的应用程序是客户端Blazor,您应该将您的对象添加到DI容器,如下所示:
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IHttpContentFormatter>();
}
public void Configure(IComponentsApplicationBuilder app)
{
app.AddComponent<App>("app");
}
}在您的组件中,您可以像这样注入对象:
@inject IHttpContentFormatter HttpContentFormatter 发布于 2019-08-14 09:22:57
我是这样做的:
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IHttpContentFormatter, HTTPContentFormatter>();
}AddXxxx方法的第二个类型参数是您希望实现IHttpContentFormatter接口的具体类型。然后@Inject声明就会像你说的那样工作。
https://stackoverflow.com/questions/57162679
复制相似问题