In ASP.NET Core, when configuring services I notice that it's usually done by extension methods that have prefix Add*
.
Similarly, when configuring middleware pipeline, we have extension methods with Use*
prefix.
For example when adding the authentication services:
services.AddAuthentication("MyAuthService")
And then we add the Authentication middleware
in the pipeline (which will use the Authentication services
that we just added above) like this:
app.UseAuthentication();
So I have few questions:
- What is the logic behind this naming convention? Where does it come from?
- When I see this code, how should I read it in my head?
- Why is
Add
not used when adding middleware to the pipeline rather thanUse
? Wouldn't it be more logical that we also useAdd
prefix because we are also adding a middleware to the pipeline? (at least to me that would make a bit more sense thanUse middleware
).
I noticed similar convention is used in NodeJs Express web apps, but I am not very familiar with Express. Is ASP.NET Core inspired by it or is it vice versa?
Is this convention also used in other web server frameworks (eg. for python, java, php, ruby on rails etc.)?
CodePudding user response:
The actions we take are described by the terms Add and Use, respectively:
The term "Add" refers to the act of adding services to the application, however this does not imply that they will be used - "Add" implies an action without any direct consequences.
The term "Use" refers to the act of actually using them in your application (as they have already been added) - the term "Use" implies an action with consequences.
Your authentication example clearly shows the logic described above:
AddAuthentication - Registers services required by authentication services (the authentication process would not take place unless you actually use these registered services in the application pipeline)
UseAuthentication - Adds the AuthenticationMiddleware to the specified IApplicationBuilder, which enables authentication capabilities.