manish sharma
manish sharma

Reputation: 11

How can I use dependency injection for my own service in blazor component class

How can I use dependency injection for my own service in blazor component class?

Component class:

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

Upvotes: 1

Views: 200

Answers (2)

John Melville
John Melville

Reputation: 3825

I did it like this:

  public void ConfigureServices(IServiceCollection services)
    {
        services.AddSingleton<IHttpContentFormatter, HTTPContentFormatter>();

    }

The second type parameter to the AddXxxx methods is the concrete type that you want to implement the IHttpContentFormatter interface. then the @Inject declaration works just like you say.

Upvotes: 0

enet
enet

Reputation: 45626

Supposing your app is client-side Blazor, you should add your object to the DI container as following:

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

        }

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

And in your Component you inject the object like that:

@inject IHttpContentFormatter HttpContentFormatter 

Upvotes: 4

Related Questions