开发者

Static Linking of libraries created on C# .NET

开发者 https://www.devze.com 2022-12-13 17:39 出处:网络
I\'m using VS2008 C#.NET. I created 3 different classes of libraries in 3 projects. I wrote an application which uses these libraries (dlls).

I'm using VS2008 C#.NET.

I created 3 different classes of libraries in 3 projects. I wrote an application which uses these libraries (dlls).

What is happening is开发者_运维技巧 each project is compiling into a class library. So, I've 3 dlls and 1 exe.

Instead I want to have these in two ways:

  1. Only class library assembly (dll) which contains 3 of them and 1 exe.
  2. just one EXE (everything inside it) :: static linking.

How could I do that? I cannot find any options for static linking in VS2008 also please mention commandline options too.


ILMerge is what you're after.

I'm not sure I'd really call this "static linking" - it's just merging several assemblies into one. (In particular, please don't get the impression that this is building a native, unmanaged executable.) However, I think it's what you're after :)

Update: ILMerge is now open source and is also available as a NuGet package:

Install-Package ilmerge 


You can place all of your code into one EXE project, use a third-party linker (google .net static linker for a number of options), or use ILMerge as illustrated here.

The third-party linkers generally also offer code obfuscation, and some can also statically link the .NET Framework.


Stumbled across this question, and found another method of achieving these ends from Jeffrey Richter (http://blogs.msdn.com/b/microsoft_press/archive/2010/02/03/jeffrey-richter-excerpt-2-from-clr-via-c-third-edition.aspx): you can embed your .dll into your executable as a resource, then overload the AssemblyResolve event to load the assembly that way. Quoting the code from the link:

AppDomain.CurrentDomain.AssemblyResolve += (sender, args) => {
   String resourceName = "AssemblyLoadingAndReflection." +
      new AssemblyName(args.Name).Name + ".dll";
   using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName)) {
      Byte[] assemblyData = new Byte[stream.Length];
      stream.Read(assemblyData, 0, assemblyData.Length);
      return Assembly.Load(assemblyData);
   }
};


In regards to Jon Skeet's answer, ILRepack is also a good open-source alternative to ILMerge. You can install it from NuGet via:

Install-Package ILRepack


You should also have a look at ILMERGE-GUI. It's a GUI wrapper for ILMerge.

0

精彩评论

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