How is execution passed from the clr to Startup class (startup.cs)?

492 views Asked by At

The Startup class in asp.net 5 strikes me as an odd duck. It isn't class Startup : ISomething or Startup : BaseSomething where the interface or base class is part of some Microsoft.AspNet.* assembly. No Startup is just a plain class with the correct magical method signatures created by convention.

How is execution passed from DNX to Startup.ConfigureServices?

Lets take for example calling:

dnx.exe . web

So the . tells dnx that it can find the project.json in the current folder. From there is finds the command associated with the key "web". So if the local project.json has this:

"commands": {
"web" : Microsoft.AspNet.Hosting --server Microsoft.AspNet.Server.WebListener --server.urls http://localhost:5000"
}

I am going to take a stab that combined it would be the equivalent of: dnx.exe . Microsoft.AspNet.Hosting --server Microsoft.AspNet.Server.WebListener --server.urls http://localhost:5000"

I also get how the dnx gathers all the sources (including dependencies) using parameters in the project.json for in memory compilation so we now have the user's assembly "MyAssembly" and all dependent assemblies available to the dnx. The dnx has loaded Microsoft.AspNet.Hosting as a managed entry point. So execution passes from the unmanaged "stub" to Microsoft.AspNet.Hosting managed assembly. Correct so far?

The next parameters are instructing Microsoft.AspNet.Hosting that it will be hosting an instance of Microsoft.AspNet.Server.WebListener (specifically on port 500 of localhost). Ok so how does Microsoft.AspNet.Server.WebListener "know" to look for a class named specifically "Startup" in "MyAssembly". Is it simply hard coded into Microsoft.AspNet.Server.WebListener? Into Microsoft.AspNet.Hosting?

The jump to Startup class seems to be the last "magic". Execution before and after that is starting to get pretty clear but I feel I am still missing something.

2

There are 2 answers

0
Victor Hurdugaci On BEST ANSWER

DNX knows how to load and execute assemblies that have class named Program which has a method named Main. You are passing Microsoft.AspNet.Hosting as the startup assembly to DNX when you run the web command.

Hosting has a Main method.

This code that eventually gets called from the Main method mentioned above has "Startup" hardcoded in it. The actual hardcode is here.

0
lgoncalves On

I'd like to add some details to Victor's answer:

I wrote a series of posts that dives into the details of bootstrapping an ASP.NET 5 application, from the DNX native host up to request handling. All those execution details are covered on the posts.