Can a C# .dll assembly contain an entry point?

Sean picture Sean · Mar 6, 2012 · Viewed 24.5k times · Source

My goal is to create an executable that will start a shadow copied application. The trick is, I want this starter program to have no external dependencies and not have to contain any knowledge about the program it has to start.

I also want it to be the only executable in the directory. In other words, I want it to "run" a .dll assembly not an .exe assembly. (I can require that the name of the .dll file being loaded into a new AppDomain be the same everytime, like Main.dll or something like that.)

It looked like AppDomain.ExecuteAssembly would do exactly what I wanted. It says it will start execution at the "entry point specified in the .NET Framework header.".

When I try to use that function I get the error "Entry point not found in assembly 'DllApp'".

The starter program I have, just trying to run the assembly:

static void Main()
{
    AppDomain domain = AppDomain.CreateDomain( "DllApp" );
    domain.ExecuteAssembly( "DllApp.dll" );
}

The application code, in a .dll file, with a default entry point:

static class Program
{
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault( false );
        Application.Run( new Form1() );
    }
}

This page on Main() functions says that "Libraries and services do not require a Main method as an entry point". It doesn't say they cannot have a default entry point either.

I have tried all the various permutations of public/private static void main, an int return type, string[] args as arguments, with a namespace, no namespace, static/non-static class, etc.

I was able to change my code to inherit from MarshalByRefObject and then use CreateInstance to create an object, but that seems like it will more tightly couple the starter to the program it is supposed to start. If I could use ExecuteAssembly, the application being started would just need a static void Main, and that is really simple and hard to mess up.

Is it possible for a .dll assembly to have a default entry point, and for ExecuteAssembly to find it, or do I just have to resign myself to going another route?

Answer

Keith Nicholas picture Keith Nicholas · Mar 6, 2012

You can compile a .NET app as an exe (which is an assembly) and rename it to a .DLL and it will act as a normal .NET .dll assembly. It will then have your Entry point.