The code below successfully recognizes internal classes which are decorated with my custom "Module" attribute, I load the assembly like this:
Assembly assembly = Assembly.GetExecutingAssembly();
However, when I load in an external module and look through its classes, it finds the classes in the external assembly but does not recognize the custom attributes:
Assembly assembly = Assembly.LoadFrom(@"c:\tests\modules\CustomModules.dll");
What do I have to specify so that C# recognizes custom attributes in external .dlls the same as it does with the internal classes?
Here is the code that successfully runs through and recognizes internal classes decorated with my "Module" attribute:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace DynamicAssembly2
{
class Program
{
static void Main(string[] args)
{
var modules = from t in GetModules()
select t;
foreach (var module in modules)
{
ModuleAttribute[] moduleAttributes = GetModuleAttributes(module);
Console.WriteLine(module.FullName);
foreach (var moduleAttribute in moduleAttributes)
{
Console.WriteLine(moduleAttribute.Description);
}
}
Console.ReadLine();
}
public static IEnumerable<Type> GetModules()
{
//Assembly assembly = Assembly.LoadFrom(@"c:\tests\modules\CustomModules.dll");
Assembly assembly = Assembly.GetExecutingAssembly();
return GetAssemblyClasses(assembly)
.Where((Type type) => {return IsAModule(type);});
}
public static IEnumerable<Type> GetAssemblyClasses(Assembly assembly)
{
foreach (Type type in assembly.GetTypes())
{
Console.WriteLine(type.FullName);
yield return type;
}
}
public static bool IsAModule(Type type)
{
return GetModuleAttribute(type) != null;
}
public static ModuleAttribute GetModuleAttribute(Type type)
{
ModuleAttribute[] moduleAttributes = GetModuleAttributes(type);
Console.WriteLine(moduleAttributes.Length);
if (moduleAttributes != null && moduleAttributes.Length != 0)
return moduleAttributes[0];
return null;
}
public static ModuleAttribute[] GetModuleAttributes(Type type)
{
return (ModuleAttribute[])type.GetCustomAttributes(typeof(ModuleAttribute), true);
}
}
}
Here is my custom Mdoule attribute:
using System;
namespace DynamicAssembly2
{
[AttributeUsage(AttributeTargets.Class)]
public class ModuleAttribute : Attribute
{
public string Description { get; set; }
}
}
Here is a custom module:
namespace DynamicAssembly2
{
[Module(Description="This is the main customer class.")]
class Customers
{
}
}