How to determine if a method is called from a Windows service in .Net (managed) code

How can I tell if a method I am writing in managed code is a call from an interactive application or Windows service?

+1


a source to share


5 answers


I think I may have figured it out (at least it works for my needs - your mileage may vary depending on what you are trying to do). There, a property hangs from an Environment object called "UserInteractive". It tells you if you are working in a context with desktop access.



+1


a source


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.

+1


a source


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.
0


a source


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.

0


a source


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.

0


a source







All Articles