0
votes

I am studying Asp.NET Core 3.1.

Noticed that when we started the project. It will go to the ConfigureServices and inject a service.

   public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllersWithViews();
    }

My question is why services can use those extension methods?

I checked the framework.

IServiceCollection is an interface. There is the properties called Services in IMvcBuilder interface.

but still don't understand what the relationship is. How .NET knows IServiceCollection services can use the extension methods such as AddControllersWithViews(), AddMvc()...etc ? enter image description here

Thanks.

1

1 Answers

0
votes

IServiceCollection represents the way to register services into the IoC container. The extension methods there are common for simplifying the configuration of other services.

Extension methods require a few things:

  1. A method with a this parameter
    public static void AddSomething(this IServiceCollection ...)
    
  2. A namespace import to the namespace that contains the class that has the extension method.

IMvcBuilder just happens to be what AddMvc returns to further configure ASP.NET Core MVC.