Skip to content

Instantly share code, notes, and snippets.

@juanonsoftware
Last active June 1, 2018 07:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save juanonsoftware/5b8d244470d57eb6b05512deb0184f56 to your computer and use it in GitHub Desktop.
Save juanonsoftware/5b8d244470d57eb6b05512deb0184f56 to your computer and use it in GitHub Desktop.
A class that helps to load embeded dll files into app domain
public class EmbededAssemblyHelper
{
private static Assembly _embededResourcesAsm;
private static string _embededResourcesNamespace;
public static void Setup(Assembly embededResourcesAsm, string embededResourcesNamespace)
{
_embededResourcesAsm = embededResourcesAsm;
_embededResourcesNamespace = embededResourcesNamespace;
}
public static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
if (_embededResourcesAsm == null)
{
throw new NotSupportedException("You must setup the helper before this event");
}
// ReSharper disable once AssignNullToNotNullAttribute
var embededLibs = _embededResourcesAsm.GetManifestResourceNames().Where(x => x.StartsWith(_embededResourcesNamespace));
// The args.Name could be full qualified name or just short name like below example
// log4net (in .net 4.6)
// or args.Name: log4net, Version=2.0.8.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a (in .net 4.5)
var asmName = args.Name;
if (args.Name.Contains(","))
{
asmName = args.Name.Substring(0, args.Name.IndexOf(",", StringComparison.InvariantCultureIgnoreCase));
}
var resourceName = embededLibs.FirstOrDefault(x => x.EndsWith(string.Format("{0}.dll", asmName)));
if (string.IsNullOrWhiteSpace(resourceName))
{
Debug.WriteLine(@"/!\ Not find any resource embeded for " + asmName);
return null;
}
var res = _embededResourcesAsm.GetManifestResourceStream(resourceName);
var bytes = new byte[res.Length];
res.Read(bytes, 0, (int)res.Length);
return Assembly.Load(bytes);
}
}
@juanonsoftware
Copy link
Author

juanonsoftware commented Jun 1, 2018

Usage is just as below:

    static Program()
    {
        EmbededAssemblyHelper.Setup(typeof(EmbededLibsType).Assembly, typeof(EmbededLibsType).Namespace);
        AppDomain.CurrentDomain.AssemblyResolve += EmbededAssemblyHelper.CurrentDomain_AssemblyResolve;
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment