Quantcast
Channel: Windows Presentation Foundation (WPF) forum
Viewing all articles
Browse latest Browse all 18858

How to instantiate an interface from a dynamically loaded assembly?

$
0
0

How can an interface be instantiated that is in a dynamically loaded assembly?

Assume that three assemblies exist, one that is in command to the other two and defines the interface IExample. The second assembly, DecoupledAssembly, implements a class named Example which is derived from the interface IExample. The third is an application. It wants to load the DecoupledAssembly and then instantiate IExample.

Here's what IExample looks like.

public interface IExample
{
    void Method1( string s );
}

Here's what the sample DecoupledAssembly looks like.

namespace DecoupledAssembly
{
    public class Example : IExample
    {
        public void Method1( string s )
        {
            Console.WriteLine( s );
        }
    }
}

Here's what the application that wants to instantiate the interface looks like.

do { try { // Load the assembly. This works. System.Reflection.Assembly decoupledAssembly =
System.Reflection.Assembly.LoadFrom( "DecoupledAssembly.dll" ); if (decoupledAssembly == null) { break; } // Load the interface. This fails. IExample example = decoupledAssembly.CreateInstance( "IExample" ) as IExample; if (example == null) { break; } } catch (Exception ex) { Console.WriteLine( ex.ToString() ); } } while (false);


So, obviously, I am doing something wrong with extracting the interface out of the DecoupledAssembly. What would be the correct way to do this?


Richard Lewis Haggard


Viewing all articles
Browse latest Browse all 18858

Trending Articles