简体   繁体   中英

ASP.net Web API 2:How WebApiConfig.Register is being called without passing parameter in Global.asax.cs file

I am creating restful service using ASP.Net WEB API 2.0. While reviewing the code, below is the code of RouteConfig.cs class file:

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
}

In Global.asax.cs file the RegisterRoutes method of RouteConfig class is being called as below:

public class WebApiApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        GlobalConfiguration.Configure(WebApiConfig.Register);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
    }
}

I am very curious to know :

  1. How WebApiConfig.Register method is being called as we are not passing any parameter explicitly.

GlobalConfiguration.Configure accepts Action<HttpConfiguration> as a parameter. This is in a way "reference to a fucntion". When you use WebApiConfig.Register without () it's not the call to a function but rather a delegate that is passed as a parameter. WebApiConfig.Register has a correct signature, ie accepts HttpConfiguration as a parameter, that's why you can just pass it on to GlobalConfiguration.Configure .

Later the framework will call the method that you have passed and supply the parameter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM