开发者

Add DLL programmatically at runtime

Using C#, I cre开发者_如何学Cate a DLL at runtime and now I want to add it as a reference to my project at runtime.

I tried using the LoadFrom method, but it doesn't work.

How can I do this?


First you should load the dll

Assembly assembly = Assembly.LoadFrom("dllPath");

Then you may need to add the assembly to the app domain

AppDomain.CurrentDomain.Load(assembly.GetName());

After that you can load any type from this assembly

Type t = assembly.GetType("typeName");

Then using reflection you can execute methods on this type

Note that you may need to add the below in the configuration file.

<runtime>
  <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
    <probing privatePath="dlls folder"/>
  </assemblyBinding>
</runtime>


LoadFile vs. LoadFrom

Be careful - these aren't the same thing.

LoadFrom() goes through Fusion and can be redirected to another assembly at a different path but with that same identity if one is already loaded in the LoadFrom context. LoadFile() doesn't bind through Fusion at all - the loader just goes ahead and loads exactly* what the caller requested. It doesn't use either the Load or the LoadFrom context. So, LoadFrom() usually gives you what you asked for, but not necessarily. LoadFile() is for those who really, really want exactly what is requested. (*However, starting in v2, policy will be applied to both LoadFrom() and LoadFile(), so LoadFile() won't necessarily be exactly what was requested. Also, starting in v2, if an assembly with its identity is in the GAC, the GAC copy will be used instead. Use ReflectionOnlyLoadFrom() to load exactly what you want - but, note that assemblies loaded that way can't be executed.)

LoadFile() has a catch. Since it doesn't use a binding context, its dependencies aren't automatically found in its directory. If they aren't available in the Load context, you would have to subscribe to the AssemblyResolve event in order to bind to them.

ref Suzanne Cook's .NET CLR Notes


Use Assembly.LoadFile method and then run code inside it using reflection.


Actually Assembly.Load is usually what you'd want, not LoadFrom and not LoadFile:

Which context is right for you? In general, I strongly recommend that you use the Load context whenever possible

http://blogs.msdn.com/b/suzcook/archive/2003/05/29/57143.aspx


You cannot add dll to a project when project is already running. However, you can load the dll using Assembly.LoadFrom( filename). Normally such scenerio is used for SOA or plugin based projects. You can use interface to specify the type structure and load the dll and use it.


You could use the Assembly.LoadFrom method to dynamically load an assembly at runtime.


This is very simple in .NET: http://msdn.microsoft.com/en-us/library/1009fa28.aspx

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜