views:

26

answers:

1

I am trying to convert Java libs to c# libs. I am stuck at a place and could not find any solution via googling. The issue is in c# Class Lib i want to write assembly load/init event handler, is it possible as in Java it seems is? In java the code is.

public class abc implements ServletContextListener {

public void contextInitialized(ServletContextEvent event) {
    //do something
}

public void contextDestroyed(ServletContextEvent event) {
    //do something
}
}

what would be its equivalent in c#?

+2  A: 

There is an AssemblyLoad event in the AppDomain class that may be what you are looking for:

    private void SomeMethod() {
        AppDomain.CurrentDomain.AssemblyLoad += new AssemblyLoadEventHandler(CurrentDomain_AssemblyLoad);
    }
    void CurrentDomain_AssemblyLoad(object sender, AssemblyLoadEventArgs args) {
        // Code to initialize here...
    }
Steve Ellinger
Thanks Steve, excellent answer but where this "SomeMethod" is to be written itself? as i have almost 20 classes in the .dll assembly
Adeem
Unfortunately you cannot put the code in the assembly itself since by definition if you are running code in an assembly it is already loaded and the event has already fired. I am not sure as to your requirements: is your library statically loaded or dynamically loaded; that is to say, will people typically have a reference to your library or will they use the Assembly.Load method? I am not familiar with Java, I suspect that the AppDomain.AssemblyLoad event is the closest you can get to what you described, there maybe significant differences however.
Steve Ellinger
Its not a static lib and this is a shared lib and many projects will use this library by referencing it. Yes i understand that bit that we cannot write code in assembly but i thought maybe we inherit some interface or write some partial class for that
Adeem
The best place put the event subscription is in the Main method of the application as the first line of code in the method. In a VS generated C# project the Main method is typically in the Program.cs file.
Steve Ellinger