Wednesday, February 10, 2016

Consuming Services in ASP.NET Core MVC View

Exclusive Amazon Deals
In continuation to my previous post on injecting services in controller, this time I'm writing on how to inject services directly in MVC View. In order to achieve this, a new keyword @inject is used.
Here I'm not writing entire code again as it can be referred from my previous article.

Let's register the service in ConfigureServices method as:

public void ConfigureServices(IServiceCollection services)
        {
           ...
           ...
           services.AddTransient<IGUIDService,GUIDService>();
        }

Next is to inject service inside a View as:
@inject IGUIDService guidService

Now service is injected and available for use. Let's quickly use it:

@using CustomTagHelper.Services;
@inject IGUIDService guidService

<p>@guidService.GenerateGUID()</p>

Run your application and you will be able to see the required output as:









Hope you enjoyed learning :)

No comments:

Post a Comment