Last active
June 1, 2018 07:07
-
-
Save juanonsoftware/5b8d244470d57eb6b05512deb0184f56 to your computer and use it in GitHub Desktop.
A class that helps to load embeded dll files into app domain
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage is just as below: