Arunachalam
Arunachalam

Reputation: 6077

Loading assemblies at run-time

My project is an application in which we load various assemblies and perform operations on them.

We are stuck at a situation where we need to add a reference to the assembly we load (which will be selected by user). So I need to add a reference to the DLL at run time.

I tried this site but here they support only microsoft DLLs like System.Security etc. I want to add a reference to a user created dll (class library).

Upvotes: 2

Views: 3288

Answers (4)

Wolf5
Wolf5

Reputation: 17180

If the assembly is in another location than the current or in the GAC, just use the AppDomain.CurrentDomain.AssemblyResolve event to deliver the assembly yourself.

Upvotes: 1

Simon Hughes
Simon Hughes

Reputation: 3574

The Composite UI Application Block facilitates the design and implementation of your client applications in three areas:

  • It allows your application to be based on the concept of modules or plug-ins.
  • It allows developers with shell expertise to build components that hide user interface complexity from the business logic development.
  • It facilitates development using patterns for loose coupling between modules.

For WPF: Take a look at Prism: patterns & practices Composite Application Guidance for WPF and Silverlight site It does the assembly loading you require and actually uses Unity internally as it's IoC container.

For non WPF: Take a look at Smart Client - Composite UI Application Block

Or alternatively: Try any of the IoC containers like Castle Windsor, autofac, unity, etc.

Upvotes: 0

Marc Gravell
Marc Gravell

Reputation: 1063864

You can't "add a reference" at runtime - but you can load assemblies - Assembly.LoadFrom / Assembly.LoadFile etc. The problem is that you can't unload them unless you use AppDomains. Once you have an Assembly, you can use assemblyInstance.GetType(fullyQualifiedTypeName) to create instances via reflection (which you can then cast to known interfaces etc).

For a trivial example:

// just a random dll I have locally...
Assembly asm = Assembly.LoadFile(@"d:\protobuf-net.dll");
Type type = asm.GetType("ProtoBuf.ProtoContractAttribute");
object instance = Activator.CreateInstance(type);

At which point I can either cast instance to a known base-type/interface, or continue to use reflection to manipulate it.

Upvotes: 8

leppie
leppie

Reputation: 117310

If you load an assembly at runtime, it will look for all its dependencies in the current location or the GAC, and load them if found, else error.

Upvotes: 0

Related Questions