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.
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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With