Loading and Unloading an external DLL into our own Visual Studio Extension type of project

  • Thread starter Thread starter vaira20ster
  • Start date Start date
V

vaira20ster

Guest
I have developed a Visual Studio Extension window. In that Extension Window, I am trying to load an external DLL (class library) and will be accessing the Class, its Methods and properties of that class inside the external DLL. Now I am allowing the user to interact with my Extension Window by choosing the methods from that DLL and allowing them to execute those methods.

Now comes the tricky part, I will be getting a newer version of that external DLL. So I need to unload my older version of external DLL and Load the newer version of external DLL.

If I load the external DLL normally using Assembly class, then it will load the DLL into the Current Domain and can't be unloaded. So I am trying to load the external DLL into a new my own AppDomain so that I can unload the AppDomain which unloads the DLL automatically.

Below is the code which I am calling it from my Extension Window code,

AppDomainSetup appSetup = new AppDomainSetup();

appSetup.ApplicationBase = @"C:\Users\xxx\AppData\Local\Microsoft\VisualStudio\15.0_60bdd44eExp\Extensions\National Instruments\Project1\1.0";
appDomain = AppDomain.CreateDomain("mydomain", null, appSetup);
var someclassObj = (someclass)appDomain.CreateInstanceAndUnwrap(Assembly.GetExecutingAssembly().FullName, typeof(someclass).FullName);


In the above code, Line#2 is necessary because it is an Extension project and runs on Visual Studio instance. If I don't specify AppDomainSetup with the Path to the Extension folder where it is running, it throws the error "Not able to load the DLL as one of the dependencies is not found". So after configuring the Extension folder path to AppDomainSetup, it is able to get into someclass constructor and loads the DLL into a new Domain.

Now the problem that I am facing is, when it tries to create the object for the someclass, it throws the error "Unable to cast transparent proxy to type 'Namespace1.someclass". in Line#4 (CreateInstanceandUnWrap). I think it gives out the object of type Marshal instead of someclass. Please help me on this error.

Below is my someclass code for reference.


public class someclass : MarshalByRefObject
{
private static Func<object> FuncConstr { get; }
private object Instance { get; }
private static Func<object, double> FuncExecute { get; }
public static Assembly assembly { get; }
static someclass()
{
var assemblyPath = @"C:\xxx\yyy\Demo.dll";
assembly = Assembly.LoadFrom(assemblyPath);
Type My_Type = assembly.GetType("NameSpace1." + "Class1");

FuncConstr = () => Activator.CreateInstance(My_Type);

MessageBox.Show("static class");
}

public someclass() => Instance = FuncConstr();

public string getsomething() => FuncExecute(Instance).ToString();
}


Any help on this would be really helpful.


Continue reading...
 
Back
Top