Tuesday, May 15, 2018

Dependency Injection in Blazor

[Content in this post is based on Blazor 0.3.0]

In my last post, I wrote about how you can get yourself started on Blazor. If you are new to Blazor, maybe you can read it first, so you can easily catch along with this. In this post let’s see how we can use Dependency Injection within Blazor.

DI is a first class citizen is Blazor meaning Blazor has DI built in.

If you have a look at the Program.cs of an Blazor application, you should be seeing this.
public class Program
{
    static void Main(string[] args)
    {
        var serviceProvider = new BrowserServiceProvider(services =>
        {
                
        });
 
        new BrowserRenderer(serviceProvider).AddComponent<App>("app");
    }
}
Now we have the following Interface and the implementation.

IMyService.cs
interface IMyService
{
    string Echo();
}

MyService.cs
public class MyService : IMyService
{
    public string Echo()
    {
        return "Hello Blazor";
    }
}

And say, I want to be able to use MyService.Echo() method in any of my component.

First what we need to do is register the service.
image
Service Registration
Here you can see that we can use the ServiceDescriptor to register the service mainly in three different ways, Scoped, Singleton and Transient.
  • Scope,d: Currently no scoping is supported. Behaves like Singleton.
  • Singleton: Single instance. When requested, everyone gets the same instance.
  • Transient: When requested, gets a new instance.
All these registrations are getting added into Blazor’s DI.

For the demo, I will use Singleton.
var serviceProvider = new BrowserServiceProvider(services =>
{
    services.Add(ServiceDescriptor.Singleton<IMyService, MyService>());
})

Now let’s see how we can make use of this. I am going to modify the index.cshtml file.

There is two ways to inject a service into a component.

1. Use @inject
@page "/"
 
@inject IMyService service
 
<h1>Hello, world!</h1>
<h3>@service.Echo()</h3>
 
Welcome to your new app.
 
<SurveyPrompt Title="How is Blazor working for you?" />

2. Use [Inject] attribute
@page "/"
 
<h1>Hello, world!</h1>
<h3>@service.Echo()</h3>
 
Welcome to your new app.
 
<SurveyPrompt Title="How is Blazor working for you?" />
 
@functions{     
   [Inject]     
   IMyService service { get; set; }
}
Both of the approaches will be giving us following.
image
Output
If you have a look at the FetchData.cshtml file which is getting added when we have created a Blazor project using Visual Studio, you must have noticed injecting of HttpClient.
@page "/fetchdata"
@inject HttpClient Http
Have you wondered where that is coming from. HttpClient  and IUriHelper (Service for working with URIs and navigation state) is by default configured for DI in Blazor.

Pretty straightforward, isn't it. Hope this helps!

Happy Coding.

Regards,
Jaliya

No comments:

Post a Comment