I use the following code to load up types from assemblies annotated with my SearchableAssemblyAttribute. The goal is to be able to load my own assemblies in addition to any 3rd party assemblies.
Following this example I get the path from the GetExecutingAssembly().Location. For a web service however this will be a temp directory that contains only the executing assembly. The other assemblies are all located in sub directories of the executing assemblies parent directory.
I can go up the directory hierarchy and back down through each sub directory in order to find all the assemblies however it feels like I am missing something.
How can I load assemblies without having to worry about where the code is executing from?
private TypeCache()
{
string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); ;
foreach (string dll in Directory.GetFiles(path, "*.dll"))
{
Assembly asm = Assembly.LoadFile(dll);
if (!asm.IsDefined(typeof(SearchableAssemblyAttribute), false))
{
continue;
}
foreach (Type type in asm.GetTypes())
{
ClassIdAttribute classIdAttribute = type.GetCustomAttribute<ClassIdAttribute>(false);
if (classIdAttribute == null)
{
continue;
}
if (types.Keys.Any(c=> c.ClassId.Equals(classIdAttribute.ClassId, StringComparison.OrdinalIgnoreCase)))
{
throw new ProgramException(string.Format("The Class Id for [{0}] has already been used.", classIdAttribute.DisplayName));
}
types.Add(classIdAttribute, type);
}
}
}