Assembly? thisAssembly = Assembly.GetEntryAssembly();

if (thisAssembly is null)
{
  WriteLine("Błąd podczas odczytu wejścia do zestawu.");
  return;
}

OutputAssemblyInfo(thisAssembly);

WriteLine("Tworzenie kontekstu dla:\n  {0}\n",
  Path.GetFileName(thisAssembly.Location));

DemoAssemblyLoadContext loadContext = new(thisAssembly.Location);

string assemblyPath = Path.Combine(
  Path.GetDirectoryName(thisAssembly.Location) ?? "", 
  "DynamicLoadAndExecute.Library.dll");

WriteLine("Ładowanie:\n  {0}\n",
  Path.GetFileName(assemblyPath));

Assembly dogAssembly = loadContext.LoadFromAssemblyPath(assemblyPath);

OutputAssemblyInfo(dogAssembly);

Type? dogType = dogAssembly.GetType("DynamicLoadAndExecute.Library.Dog");

if (dogType is null)
{
  WriteLine("Błąd podczas odczytywania typu Dog.");
  return;
}

MethodInfo? method = dogType.GetMethod("Speak");

if (method != null)
{
  object? dog = Activator.CreateInstance(dogType);

  for (int i = 0; i < 10; i++)
  {
    method.Invoke(dog, new object[] { "Fido" });
  }
}

WriteLine();
WriteLine("Usunięcie kontekstu i zestawów.");
loadContext.Unload();
