Linking statically in C#

2019-01-22 07:57发布

问题:

I'm working on a module for a CMS. This module is distributed as a class library DLL.

I have several utility libraries I'd like to use in this module. Is there anyway I can link these libraries statically so I won't have to distribute several DLL's (thereby distributing my utility libraries separately)?

I would like to have only one DLL.

回答1:

You can merge your many DLLs with ILMERGE:

http://research.microsoft.com/~mbarnett/ILMerge.aspx

Haven't tried it myself. Hope it helps.


Download here:
http://www.microsoft.com/downloads/details.aspx?familyid=22914587-B4AD-4EAE-87CF-B14AE6A939B0&displaylang=en

Brief Description (from download-page)
ILMerge is a utility for merging multiple .NET assemblies into a single .NET assembly. It works on executables and DLLs alike and comes with several options for controlling the processing and format of the output. See the accompanying documentation for details.



回答2:

If you don't want to use ILMerge, see this page:

http://blogs.msdn.com/b/microsoft_press/archive/2010/02/03/jeffrey-richter-excerpt-2-from-clr-via-c-third-edition.aspx

editor's note: Jeffrey Richter advices to put your dlls into exe file as resources (For each DLL file you add, display its properties and change its “Build Action” to “Embedded Resource.”). Then a custom class loader is needed to make the executable work (At runtime, the CLR won’t be able to find the dependent DLL assemblies, which is a problem. To fix this, when your application initializes, register a callback method with the AppDomain’s ResolveAssembly event).

Be sure to change the resourceName string to point to your actual resources. (e.g. change AssemblyLoadingAndReflection to your project name.)



回答3:

The short answer for this is no! You can not link in a dll during compilation. I don't know if there is some subtle way to do this, but you would probably have to distribute the dlls along with your cms. The best way to do this is to make some kind of re-distributable.