我遇到了同样的问题并以这种方式解决了。我只用方法定义了一个IAssembyInitializer
接口void Initialize()
。在每个我想在加载后执行一些代码的程序集中,我定义了一个实现这个接口的类。我定义了一个属性来指定程序集中实现此接口的类(否则您可以通过反射找到它们,但我更喜欢这种方式):
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
public class AssemblyInitializerAttribute : Attribute
{
AssemblyInitializerAttribute ()
{
}
AssemblyInitializerAttribute (string typeName)
{
TypeName = typeName;
}
public string TypeName;
}
属性在 AssemblyInfo 中以这种方式设置:
[assembly: AssemblyInitializerAttribute ("MyNamespace.AnAssemblyInitializer")]
最后,在应用程序的主程序集中,我向 AssemblyLoad 事件注册了一个执行所有初始化的方法:
AppDomain.CurrentDomain.AssemblyLoad += new AssemblyLoadEventHandler(NewAssemblyLoaded);
static void NewAssemblyLoaded(object sender, AssemblyLoadEventArgs args)
{
Assembly anAssembly = args.LoadedAssembly;
AssemblyInitializerAttribute[] initializers = (AssemblyInitializerAttribute[])anAssembly .GetCustomAttributes(typeof(AssemblyInitializerAttribute), false);
foreach (AssemblyInitializerAttribute anInit in initializers)
{
Type initType = anInit.TypeName != null ? anAssembly.GetType(anInit.TypeName) : null;
if (initType != null && initType.GetInterface("IAssemblyInitializer") != null)
{
IAssemblyInitializer anInitializer = (IAssemblyInitializer)Activator.CreateInstance(initType);
anInitializer.Initialize();
}
}
}