Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Who Are You Running From?

10 May 2013 1  
Determine the nature of the entry assembly

Introduction

Once again, I have a tip that came directly from my work-a-day development efforts. We have a plugin-based windows service, and when developing the associated plugin DLLs, we create a test harness app in the solution so we can debug the plugins on our local box before we deploy them.

All of the plugins have an output folder, and when deployed, the output folder is located on a remote machine. To avoid interfering with a previous version of a given plugin that might be running (when debugging), we need to specify a local folder to receive the output that the plugin generates.

Prior to me taking over the coding for this particular task, the process of debug/deployment involved changing the DLL's config file to change the output folder, depending on whether we were debugging or deploying the plugin. As you might guess, there have been several times where someone forgot to restore the deployed version of the path, which led me to the solution presented below.

All I needed to do was determine whether the DLL was loaded by an application, or if it was loaded by a service. Thanks to reflection, we can easily make this determination. The code below could easily be reduced to a single line, but I kept it separated out so it was easier to see what was happening. 

The end result is that now I can include BOTH the deployed and local version in the config file, and don't have to worry about making sure the correct key entry is commented out in the config file. Given the nature of my swiss-cheese-like memory, that can only be a good thing.

The Code

using System.Reflection;

private bool RunningInService()
{
    bool isService = false;

    // Get the assembly that's actually running our plugin DLL
    Assembly entry = Assembly.GetEntryAssembly();

    // Get the entry point method that was called to enter the host assembly.
    System.Reflection.MethodInfo entryPoint = entry.EntryPoint;

    // see if it's a service
    isService = entryPoint.ReflectedType.BaseType.FullName == "System.ServiceProcess.ServiceBase";

    return isService;
}

History

  • 10 May 2013:Initial release

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here