I would 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.
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
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
来源:https://stackoverflow.com/questions/7655222/is-there-an-equivalent-of-application-start-for-a-class-library-in-c-sharp