Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically load references in parent assemblies in C#

Tags:

c#

.net-4.0

How do I get a list of references in the parent assembly in C#. I'm thinking of a DLL that is loaded into another program, and the driver needs to use some of the parent assembly references in reflection and serialization. So far, I haven't tried anything as I'm not sure where to start.

like image 279
Arlen Beiler Avatar asked Dec 29 '25 18:12

Arlen Beiler


1 Answers

It's pretty classic reflection issue, when you need to load an assembly and the assembly contains references, which are not referenced to the calling assembly.

Basically, you should load the assembly inside separate application domain.

e.g., you have a project ProxyDomain with a class ProxyType:

public class ProxyType : MarshalByRefObject
{
    public void DoSomeStuff(string assemblyPath)
    {
        var someStuffAssembly = Assembly.LoadFrom(assemblyPath);

        //Do whatever you need with the loaded assembly, e.g.:
        var someStuffType = assembly.GetExportedTypes()
            .First(t => t.Name == "SomeStuffType");
        var someStuffObject = Activator.CreateInstance(someStuffType);

        someStuffType.GetMethod("SomeStuffMethod").Invoke(someStuffObject, null);
    }
}

And in your calling project, which contains a reference to ProxyDomain, you need to load the assembly, execute DoSomeStuff and unload the assembly resources:

public class SomeStuffCaller
{
    public void CallDoSomeStuff(string assemblyPath)
    {
        AppDomainSetup setup = AppDomain.CurrentDomain.SetupInformation;
        //Path to the directory, containing the assembly
        setup.ApplicationBase = "...";
        //List of directories where your private references are located
        setup.PrivateBinPath = "...";
        setup.ShadowCopyFiles = "true";

        var reflectionDomain = AppDomain.CreateDomain("ProxyDomain", null, setup);

        //You should specify the ProxyDomain assembly full name
        //You can also utilize CreateInstanceFromAndUnwrap here:
        var proxyType = (ProxyType)reflectionDomain.CreateInstanceAndUnwrap(
            "ProxyDomain", 
            "ProxyType");

        proxyType.DoSomeStuff(assemblyPath);

        AppDomain.Unload(reflectionDomain);
    }
}
like image 190
Olexander Ivanitskyi Avatar answered Jan 01 '26 06:01

Olexander Ivanitskyi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!