How to determine if a method is called from a Windows service in .Net (managed) code
What part of a Windows service do you want to know? Or which part of an interactive application you don't want to know? What is really important to you?
Every time I hear a request like this, it is almost always a design mistake. I would suggest multiple answers:
- Let the caller tell you which formatter to use, or
- Place the name of the formatting class in the config file. Let all formatters implement the same interface. At runtime, the first time you need a formatter, create the instance specified in the config file and call it through the common interface.
- Don't reinvent the wheel. Use the classes in System.Diagnostics, which are essentially configurable like mine # 2.
It is almost always a mistake for the code to be sensitive to the context in which it was called.
a source to share
There are at least 2 ways to do this:
- "System.Reflection.Assembly.GetCallingAssembly (). FullName" will return the name of the assembly calling your code.
- "Environment.StackTrace" will return a complete stack trace for those who call your code. You should see the name of the calling method on the line.
a source to share
You can define two different registrars: one for online applications and one for Windows service. and let the client choose which registrar he wants to use using the config file. You can also have a default registrar if customers choose the wrong registrar or forget to configure. I think it would be better to have functionality like logging and message formatting that can be customized.
a source to share
Don't know if there is a built-in capability, but take a look at the class System.Diagnostics.Process
. This is a method among other things, GetService()
maybe it will help you. If that fails, there is an item StartInfo
that might contain useful information.
If you don't mind using PInvoke, you can get the parent of the current process. If it is running under the NT AUTHORITY \ SYSTEM account and the name is service.exe, the current process is (most likely) a service.
a source to share