Due to the lack of necessary APIs for manipulating assemblies in .NET Core 1.1 and prior,
PowerShell Core needs to control assembly loading via our customized `AssemblyLoadContext` ([CorePsAssemblyLoadContext.cs][]) in order to do tasks like type resolution.
So applications that want to host PowerShell Core (using PowerShell APIs) need to be bootstrapped from `PowerShellAssemblyLoadContextInitializer`.
`PowerShellAssemblyLoadContextInitializer` exposes 2 APIs for this purpose:
`SetPowerShellAssemblyLoadContext` and `InitializeAndCallEntryMethod`.
They are for different scenarios:
-`SetPowerShellAssemblyLoadContext` - It's designed to be used by a native host
As shown below, you can insert your business logic code directly in the `Main` method.
```CSharp
// MyApp.exe
using System;
using System.Management.Automation;
public class Program
{
static void Main(string[] args)
{
// My business logic code
using (PowerShell ps = PowerShell.Create())
{
var results = ps.AddScript("Get-Command Write-Output").Invoke();
Console.WriteLine(results[0].ToString());
}
}
}
```
However, when it comes to hosting PowerShell Core, there will be a layer of redirection for the PowerShell load context to take effect.
In a .NET Core application, the entry point assembly that contains the `Main` method is loaded in the default load context,
and thus all assemblies referenced by the entry point assembly, implicitly or explicitly, will also be loaded into the default load context.
In order to have the PowerShell load context to control assembly loading for the execution of an application,
the business logic code needs to be extracted out of the entry point assembly and put into a different assembly, say `Logic.dll`.
The entry point `Main` method shall do one thing only -- let the PowerShell load context load `Logic.dll` and start the execution of the business logic.
Once the execution starts this way, all further assembly loading requests will be handled by the PowerShell load context.
So the above example needs to be altered as follows in a .NET Core application: