Last active
August 29, 2015 14:00
-
-
Save imwower/11206507 to your computer and use it in GitHub Desktop.
dynamic load assemblies from asp.net project folder
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
//folder is virtual path | |
private void LoadAssemblies(string folder) | |
{ | |
try | |
{ | |
var directory = new DirectoryInfo(HostingEnvironment.MapPath(folder)); | |
var binFiles = directory.GetFiles("*.dll", SearchOption.AllDirectories).ToList(); | |
if (binFiles.Count == 0) | |
{ | |
logger.Warn("no dlls found!"); | |
return; | |
} | |
var interfaceType = typeof(Interface); | |
var attrType = typeof(NameAttribute); | |
foreach (var dll in binFiles) | |
{ | |
var assembly = Assembly.LoadFile(dll.FullName); | |
var filters = | |
from type in assembly.GetTypes() | |
where !type.IsInterface && !type.IsAbstract | |
let attrs = type.GetCustomAttributes(attrType, false) | |
where attrs != null && attrs.Count() != 0 | |
let attr = attrs[0] as NameAttribute | |
where !string.IsNullOrEmpty(attr.Name) | |
select new | |
{ | |
ImplemetionType = type, | |
Name = attr.Name | |
}; | |
foreach (var filter in filters) | |
{ | |
container.RegisterType(interfaceType, filter.ImplemetionType, filter.Name); | |
} | |
} | |
} | |
catch (Exception exception) | |
{ | |
logger.Error(string.Format("can not load dlls at folder : {0}", folder), exception); | |
return; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment