Monday, March 16, 2020

Dynamic Assembly Loading (C# Reflection)

We will achieve following task with dynamic assembly loading in C#.

using System.Net.Http;
using System;
using System.Linq;

var client = new HttpClient();
client.BaseAddress = new Uri("http://api.open-notify.org/astros.json");
string result = client.GetStringAsync("").Result;


Don't add System.Net.Http dll to your reference list. It will be automatically loaded from GAC.

using System;
using System.Linq;
using System.Reflection;

//We don't have "using System.Net.Http" 

//Load System.Net.Http
string name1 = "System.Net.Http,Version=4.0.0.0," + "Culture=neutral,PublicKeyToken=b03f5f7f11d50a3a";
Assembly a1 = Assembly.Load(name1);

//Create HttpClient instance
Type clientType = a1.GetTypes().Where(t => t.Name.Equals("HttpClient")).Single();
object client = Activator.CreateInstance(clientType);

//Set BaseAddress on client
PropertyInfo propertyBaseAddress = clientType.GetProperties().Where(p => p.Name == "BaseAddress").Single();
Uri url = new Uri("http://api.open-notify.org/astros.json");
propertyBaseAddress.SetValue(client, url);

//Test property value
var BaseAddressValue = propertyBaseAddress.GetValue(client);

//Get HttpResponseMessage Task
var methodGetStringAsync = clientType.GetMethod("GetStringAsync", new Type[] { typeof(Uri) });
var responseTask = methodGetStringAsync.Invoke(client, new string[] { null });

//Get HttpResponseMessage result from Task
var responseType = responseTask.GetType();
PropertyInfo propResponse = responseType.GetProperties().Where(p => p.Name == "Result").Single();

var responseResult = propResponse.GetValue(responseTask);  //This is the string result


Bonus: List your loaded assemblies

Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();

foreach (Assembly a in assemblies)
{
     Console.WriteLine(a.GetName());
}


Output
mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Net.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a System.Xml, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
System.Net.Http is displayed here even not referenced in Visual Studio.

1 comments:

Henry Hill said...
This comment has been removed by a blog administrator.