简体   繁体   中英

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).

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 AppDomain s. 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.

如果程序集位于当前位置或GAC中的其他位置,请使用AppDomain.CurrentDomain.AssemblyResolve事件自行传递程序集。

如果在运行时加载程序集,它将在当前位置或GAC中查找其所有依赖项,并在找到时加载它们,否则出错。

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM