Dynamically loading assemblies and interfaces

A

Andy Walldorff

Given the following code....

// FooBar.cs, builds Activate.dll

using System;

public interface IFoo
{
void Bar();
}

public class FooBar : IFoo
{
public FooBar()
{
}

public void Bar()
{
Console.WriteLine( "FooBar" );
}
}
// End of FooBar.cs

// DoActivate.cs, builds DoActivate.exe
using System;
using System.Reflection;

class Class1
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
IFoo ifoo;
Object obj;

try
{
Assembly a = Assembly.LoadFrom( "Activate.dll" );
Type[] ts = a.GetTypes();
foreach( Type t in ts )
{
if( t.Name == "FooBar" )
{
if( t.GetInterface( "IFoo" ) != null )
{
obj = Activator.CreateInstance( t );
ifoo = obj as IFoo;
if( ifoo == null )
Console.WriteLine("didn't get object" );
else
Console.WriteLine("got object" );
}
else
Console.WriteLine( "Object does not support
IFoo" );
}
}
}
catch( Exception e )
{
Console.WriteLine( "Caught exception {0}", e );
}
}
}
// End of DoActivate.cs

Why is ifoo null? I always get "didn't get object" and yet everything
appears correct, at least to my untrained eye. Thanks in advance!
 
A

Andy Walldorff

Mattias said:
Andy,

Why are you using Assembly.LoadFrom on an assembly that you obviously
have referenced at design time?
Ultimately I want to be able to dynamically load other implementations
of IFoo. This is just a trivial example to display the problem I am
having, not with LoadFrom (it seems to work fine), but with attempting
to treat the returned object as an IFoo. Everything seems to say I
should be able to do this (i.e. code samples, the fact that GetInterface
says it's available, ...), yet when I actually try to cast the object
to an IFoo, it fails.

Interestingly enough, if I create the object via new, I am able to cast
it without a problem.
 
M

Mattias Sjögren

Andy,
Ultimately I want to be able to dynamically load other implementations
of IFoo.

In that case I suggest you move the IFoo definition to a separate
assembly. That would probably get rid of the problem.

This is just a trivial example to display the problem I am
having, not with LoadFrom (it seems to work fine), but with attempting
to treat the returned object as an IFoo.

If you actually read the pages I posted links to, you'd find out that
LoadFrom affects the type identity.



Mattias
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top