Yes you can. A dependent library can be embedded into resources and loaded from there manually. It is assumed that your library is already in the References project, the project is being assembled, the program is launched successfully
First, add the library as a resource to the project:
- The Project menu -> Add Existing Item ... - choose your assembly (dll, in the open dialog, select the file type Executable Files). The library appears in the project file list.
- Call the context menu on the added file, select Properties. Then install Build Actions -> Embedded Resource in the opened window.
Add the following class to your project:
public static class Resolver { private static volatile bool _loaded; public static void RegisterDependencyResolver() { if (!_loaded) { AppDomain.CurrentDomain.AssemblyResolve += OnResolve; _loaded = true; } } private static Assembly OnResolve(object sender, ResolveEventArgs args) { Assembly execAssembly = Assembly.GetExecutingAssembly(); string resourceName = String.Format("{0}.{1}.dll", execAssembly.GetName().Name, new AssemblyName(args.Name).Name); using (var stream = execAssembly.GetManifestResourceStream(resourceName)) { int read = 0, toRead = (int)stream.Length; byte[] data = new byte[toRead]; do { int n = stream.Read(data, read, data.Length - read); toRead -= n; read += n; } while (toRead > 0); return Assembly.Load(data); } } }
This class will load the dependent assembly from the resource as soon as the main program accesses it using the AppDomain.AssemblyResolve event handler.
In the class where the program entry point is located, add a static constructor and call the RegisterDependencyResolver method. For example, suppose you have a console application:
class Program { static Program() { Resolver.RegisterDependencyResolver(); } static void Main(string[] args) { // ... } }
Take care of unloading the assembly is not necessary, because it is still impossible (you can only upload the entire domain).
An example is peeped in the book by J. Richter "CLR via C #".