Skip to content
vcavalcante edited this page May 15, 2014 · 1 revision

##Princípios Fundamentais

Há uma série de princípios que contribuíram para moldar o runtime:

  • O runtime deve ser o mais independente possível. Mesmo o runtime percorrendo a árvore de dependências da sua sua aplicação, não é possível saber qual dos pacotes centrais do CLR você deseja utilizar, por isso não se pode carregar qualquer um deles antes disso. Com exceção de Roslyn, uma vez que o resolvedor de dependências que usa Roslyn efetivamente não carrega o Roslyn até depois das dependências serem percorridas.

  • Injeção de dependência através de toda a pilha. DI é uma parte essencial do KRuntime, e todas as bibliotecas que construímos em cima dela.

##Camadas

KRuntime layer diagram

###Camada 0 : Processo Nativo

Essa camada é bastante fina, cuja responsabilidade é encontrar e chamar o host de CLR Native, passando os argumentos dados ao processo para o host nativo para ser usado pelo resto do stack. Um exemplo dessa camada é o KLR.exe incluso no pacote ProjectK. KLR.exe seria utilizado para cenários como compilar e executar diretamente da linha de comando quando usar self-hosting em ambiente de desenvolvimento.

####Usando o KLR:

klr.exe --core45 --lib {paths} --appbase {path} [ProgramName]

  • --core45 | --net45 : Essa opção diz ao KLR.exe qual CLR deve ser carregada, --core45 diz ao KLR.exe para carregar a Core CLR específica ao Native Host, --net45 diz para tentar carregar a Desktop CLR.
  • --lib {paths} : Caminhos conhecidos de onde serão carregados os arquivos dll de assemblies compiladas. Esses diretórios serão de onde o Managed Entry Point, Layer 2, poderá carregar assemblies.
  • --appbase {path} : Diretório de base da aplicação, sendo por padrão %CD%
  • [ProgramName] : Esse é o nome de uma assembly que está em algum caminho indicado em -lib e contém o ponto de entrada Program::Main, sendo o valor padrão appbase\project.json. Na maioria dos casos esse nome é o host da aplicação (Microsoft.Net.ApplicationHost) que contém a corrente do carregador. No entanto, se sua aplicação tem um ponto de entrada e ela, além de suas dependências, está compilada em assemblies no --libpath então é possível simplesmente colocar o nome da assembly com o ponto de entrada. Isso ignora a corrente de carregamento e inicia sua app.

A maioria desses parâmetros são usados por partes de nível mais alto no stack, o único argumento usado diretamente pelo KLR.exe é a chave de CLR (--core45 | --net45).

###Layer 1 : CLR Native Host

This layer is the specific to the version of the CLR that you are using and has two main responsibilities:

  1. Boot the CLR, how this is achieved depends on the version of the CLR. For Core CLR the process involves loading coreclr.dll, configuring and starting the runtime, and creating the AppDomain that all managed code will run in.

  2. Calling the Managed Entry Point, Layer 2. When the entry point of the Native Host returns this process will then cleanup and shutdown the CLR. i.e unload the app domain and stop the runtime.

###Layer 2 : Managed Entry Point

This layer is the first layer that is written in managed code, it is responsible for:

  1. Creating the LoaderContainer that will contain the required ILoaders. An ILoader is responsible for loading an assembly by name. When the CLR asks for an assembly to be resolved the LoaderContainer will resolve the required assembly using its ILoaders.

  2. Provide the root ILoader that will load assemblies, and satisfy dependencies, from the provided --libpath.

  3. Call the main entry point of the provided program.

###Layer 3: Application host / Application

If a user compiles their entire application to assemblies on disk in the libpath then this layer is your application. To do this you pass the name of the assembly containing your applications entry point in the [ProgramName] argument and layer 2 will invoke it directly. However, in all other scenarios you would use an application host to resolve app dependencies and run your app. Microsoft.Net.ApplicationHost is the application host provided in the runtime, and has a few responsibilities:

  1. Walks the dependencies in the project.json and builds up the closure of dependencies the app will use. The dependency walking logic is described in more detail

  2. Adds an ILoader to the LoaderContainer that can load assemblies from various sources, NuGet, Roslyn, etc.

  3. Calls the entry point of assembly name given as the next argument given to KLR.exe

###Layer 4 : Application

As the name says, this is the developer’s application code when running on the application host.