Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is GlobalConfiguration.Configuration.EnsureInitialized() in Global.asax ASP.Net Web API

Under my WebApi project, I don't know what this line GlobalConfiguration.Configuration.EnsureInitialized() is doing there in Global.asax Application_Start() method. Even every thing is working good without this.Then why is this for?

Is it necessary to be here? If yes then why? Can any one explain its need and purpose in detail.

protected void Application_Start()
{   
    AreaRegistration.RegisterAllAreas();
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);

    ////////////      What is this for   ////////////////
    GlobalConfiguration.Configuration.EnsureInitialized();
}

NOT A DUPLICATE : In stack overflow many people suggest to use EnsureInitialized().But Why to use it? Where it comes from? Is it part of webApi2 or something else? These are are the things I want to know. MSDN itself has no explanation for this.

like image 698
Malik Khalil Avatar asked Jun 11 '16 23:06

Malik Khalil


1 Answers

Per MSDN:

HttpConfiguration.EnsureInitialized Method

Invoke the Intializer hook. It is considered immutable from this point forward. It's safe to call this multiple times.

More Information

As this answer points out, this was likely put into your application at some point because of a change to the way that Web API is supposed to be registered in Web API v1 vs Web API v2.

Anyone who didn't make the change after upgrading Web API would have received the error message:

The object has not yet been initialized. Ensure that HttpConfiguration.EnsureInitialized() is called in the application's startup code after all other initialization code.

Unfortunately, the solution given in the error message is misleading. What you are actually supposed to change while upgrading from V1 is to replace this line:

WebApiConfig.Register(GlobalConfiguration.Configuration);

with this line:

GlobalConfiguration.Configure(WebApiConfig.Register);

The latter method internally calls EnsureInitialized so you don't have to from your startup code.

I noticed that you don't have either of these Web Api initializers in your configuration, so I would recommend that you change your startup as follows:

protected void Application_Start()
{   
    AreaRegistration.RegisterAllAreas();
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    GlobalConfiguration.Configure(WebApiConfig.Register);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
}
like image 199
NightOwl888 Avatar answered Oct 23 '22 06:10

NightOwl888