I wou开发者_如何学Cld like to execute certain code in a class library when it is instantiated from another assembly. Is there an entry point or bootstrap for a class library? I thought that a static method Main would do the trick but I was wrong.
Applications for this might be configuring and instantiating a logger singleton, unhandled exception handler, etc.
A library as it is, has not an starting point. When you are instancing a class of a library the first instruction you call is the constructor of the class (new) and its base constructors if they are on the constructor definition.
AppDomain.AssemblyLoad Event which occurs when an assembly is loaded. Probably that can be used to call an initialize method in your class library.
public static void Main()
{
AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.AssemblyLoad += new AssemblyLoadEventHandler(MyAssemblyLoadEventHandler);
}
static void MyAssemblyLoadEventHandler(object sender, AssemblyLoadEventArgs args)
{
Console.WriteLine("ASSEMBLY LOADED: " + args.LoadedAssembly.FullName);
//If this is the assembly that you want to call an initialize method..
}
Below are two similar threads
how to write class lib's assembly load/init event handler
.Net: Running code when assembly is loaded
The best and safe way is to design your library so that the caller will initialize your library when they know they can.
When an assembly is loaded, the CLR employes a lot of machinery to have the job done, starting from how the inner platform is designed to load modules up to the CLR itself. Each involved actor has their own limitations.
Executing code when a module is loaded is not the best practice on Win32 for the same reason: you cannot know what your caller is doing; also, the changes your doing could possibly alter the current AppDomain, but may not plbe propagated in all the other AppDomain of the application.
A conscious initialization method is the cleanest way to let the caller to control the initialization of your assembly.
All the other answers partially address the issue, but could introduce unwanted side effects and non deterministic behaviors.
Have you looked into the PreApplicationStartMethodAttribute?
using System.Web;
[assembly: PreApplicationStartMethod(typeof(ClassLibrary.Startup), "Start")]
namespace ClassLibrary
{
public class Startup
{
public static void Start()
{
// do some awesome stuff here!
}
}
}
More detail: http://dochoffiday.com/professional/simulate-application-start-in-class-library
精彩评论