JumpStart # 51 – Dependency Injection into Views in ASP.Net Core

In this jumpstart, we are going to see how to inject dependencies into a View in ASP.Net Core. This feature is extremely useful when we need to use certain functionality or data in views and without including them in regular controller models. For example, populating master data to some controls like select, formatting different data and using application wide features like Globalization and localization.

NOTE: Updated this tutorial on 2/26/2017 with MSBuild based Dotnet SDK.

This tutorial is executed using below Dotnet CLI version.

image 

We are going to inject Configuration data into Index View (which comes by default when we create a new ASP.Net Core Project). Lets get started by adding a test setting in appsettings.json file.

{
  "TestSetting": "TestValue",
  "ApplicationInsights": {
    "InstrumentationKey": ""
  },
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft": "Information"
    }
  }
}

Resolve the configuration service in Startup class as shown below.

public Startup(IHostingEnvironment env)
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
        .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
        .AddEnvironmentVariables();

    Configuration = builder.Build();
}

public IConfigurationRoot Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton<IConfigurationRoot>(Configuration);
    services.AddMvc();            
}

Now lets inject configuration into Index view as shown below.

@using Microsoft.Extensions.Configuration
@inject IConfigurationRoot config

<div>@config["TestSetting"]</div>

Run the application and configuration value should be displayed on page as shown below. In the similar way we can inject any service which is configured in Startup class.

image

That’s it for now. Happy Coding and Stay Tuned!!!

You may also like...