Newer versions of ASP.NET have added exciting new functionality to Razor views. ASP.NET developers have never had it so good. In this short but simple post, we’ll walk through the steps necessary to inject a dependency into our views using ASP.NET dependency injection infrastructure.
Service Registration
All newer ASP.NET applications register their dependencies within the ConfigureServices
method found within the Startup
class. This method allows us to add any dependencies for use across our application. In this example, we will be registering a PuppyService
.
public class PuppyService
{
public Puppy Adopt()
{
return new Puppy {Name = "Clifford"};
}
}
public class Puppy
{
public string Name { get; set; }
}
We can register our newly created PuppyService
as a Transient
service. ASP.NET will create our service every time we ask for it. We can also choose to register our services as a Singleton
or Scoped
depending on our specific needs.
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
services.AddTransient<PuppyService>();
}
View Injection
ASP.NET has added an @inject
helper as part of the latest Razor view engine. This helper calls into the ASP.NET dependency injection mechanism and pulls out the required service. Let’s take a look at an example view.
@page
@model IndexModel
@inject PuppyService Puppies
@{
ViewData["Title"] = "Home page";
var puppy = Puppies.Adopt();
}
<div class="text-center">
<h1 class="display-4">@puppy.Name</h1>
</div>
Let’s break down the use of the @inject
useage:
- We use the
@inject
at the top of our Razor view. - We follow up on the keyword with the type of dependency. In this case, it is
PuppyService
. - Finally, we give our injected dependency a name,
Puppies
.
Once the Razor view has the dependency injected, we can use that dependency like we would any other variable reference. Let’s see the result of our PuppyService
.
Conclusion
Having the dependency injection pipeline be integrated into the Razor View engine should open up a world of new possibilities for developers. It is a valuable tool for building web applications, but like all new features, developers should consider its appropriate usage. I hope you found this post helpful, and please leave a comment below.