首页 > 解决方案 > 如何在 blazor 组件类中为我自己的服务使用依赖注入

问题描述

如何在 blazor 组件类中为我自己的服务使用依赖注入?

组件类:

[Inject]
public HttpContentFormatter IHttpContentFormatter { 
     get; 
     set; 
}

标签: blazor

解决方案


假设您的应用程序是客户端 Blazor,您应该将对象添加到 DI 容器,如下所示:

public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton<IHttpContentFormatter>();

        }

        public void Configure(IComponentsApplicationBuilder app)
        {
            app.AddComponent<App>("app");
        }
    }

在您的 Component 中,您可以像这样注入对象:

@inject IHttpContentFormatter HttpContentFormatter 

推荐阅读