Search code examples
c#.net-assemblyappdomaincsharpcodeproviderobjectbrowser

Unload Assembly or AppDomain after Use (like in Object Browser)


I am trying to load external Assembly to list out all Types, Methods and Properties during run time, just like Object Browser in Visual Studio. My requirement is, I want to Load external Assembly list out its Members in a treeview and Unload the Assembly or AppDomain after the use. Later in the same project I am using the same assembly to modify and add some more code to it. Since I have already opened the assembly, CompileAssemblyFromFile is not allowing me to Compile and produce the output. How can I deal with this situation? How is Object Browser works in Visual Studio without creating the instance of Assembly or if at all it is created, how to unload it after usage?

P.S.

I have already tried to use another AppDomain to load the assembly but did not success. As the treeview is created in main appdomain, I cannot access this in custom appdomain to add nodes.


Solution

  • Based on Mathieu Guindon's Comment. I am loading assembly in my ASP.Net Web API and Serializing the assembly content to JSON Array. Later in my client application I am Deserializing the response with the help HttpClient and populating the WinForms TreeView.

    Here's how I did. Sample code.

    //Action Model
    public class ActionModel
    {
       public string ActionName {get;set;}
       public IList<MethodInformation> ActionMethods {get;set;}
    }
    
    public class MethodInformation
    {
       public string MethodName {get;set;}
       public IList<ParameterInformation> GetParameters {get;set;}
    }
    
    //API
    public Object Get(string id)
    {
        switch(id)
        {
            case "Assembly1":
               Type[] typesInAssembly = Assembly.LoadFrom(pathToAssembly).GetTypes();
               
               List<ActionModel> actionModel = new List<ActionModel>();
               
               for(var t in typesInAssembly)
               {
                   /* add the items to the List actionModel */
               }
               return actionModel;
         }
    }
    

    On the client side I am having one more Class which consumes this API and parses the content by Deserializing the JSON Content and display it in treeview.

    Now the requirement is met. I can use the same copy of Assembly to show and build which was main requirement. Hope I am doing this correctly.