ASP.NET Core 2: Injecting Services into Razor pages

cat2.pngInject all the things.

Injecting dependencies into Razor pages is a new feature in ASP.NET Core designed to help with testing and simplicity.

Are cat pictures funny? The article will help answer that age-old question using a service injected into a Razor page.

Step 1: Create a service and interface

public class FunnyCatManagerIFunnyCat
    public string AreCatsFunny => "Yes";
public interface IFunnyCat
    string AreCatsFunny { get;}

Step 2: Add the IFunnyCat interface to ASP.NET Core’s dependency injection. Edit the Startup.cs file and add this:

public class Startup
    public void ConfigureServices(IServiceCollection services)
         services.AddTransient(typeof(IFunnyCat), typeof(FunnyCatManager));

Step 3: Inject the IFunnyCat implementation into a Razor page

@inject IFunnyCat CatManager
Are Cats Funny? <b>@CatManager.AreCatsFunny</b>

The result looks like this:


Cats are indeed funny

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s