shijocj
shijocj

Reputation: 23

How to find the assembly is used in a windows application or windows service

Currently I have an assembly used for a windows UI application which got a lot of logic built in and incase of errors it shows the messages to user with an ShowError() Method which internally uses Messagebox.Show(..) and then log the errors to a log file/database.

And here is my issue. I want to use the same assembly for a windows service. But when I use this assembly in a Windows service it will crash on Messagebox.show(..) because windows service will not allow UI interaction in normal mode(I know the option "Allow service to interact with Desktop", but it is not an option for me).

So what I want to do is to do some thing like this.

if(!IsWindowsService()) MessageBox.Show("Message"); Logger.Log("Message");

Here IsWindowsService() should return true if the Assembly is being used by a Windows service and false if used by a Windows Application.

Any idea how to get this?

Upvotes: 0

Views: 137

Answers (3)

si618
si618

Reputation: 16858

One way of tackling this kind of issue is abstracting your messaging (and logging, etc.) and then wiring up the appropriate classes for them via a bootstrapper using an Inversion Of Control container. For the windows service, your messaging class might not do anything, and just follow the null object pattern.

I've used Autofac for a few projects and once you wrap your head around DI/IoC it's a powerful tool.

There's a learning curve and a little extra code to write, but the clean separation of concerns should make your application(s) more maintainable and extensible. You also can avoid having your code polluted with lots of conditional statements based on the environment in which it is running.

Upvotes: 0

Tony Hopkinson
Tony Hopkinson

Reputation: 20330

All the solutions I've seen basically cheat and examine a command line parameter passed into the executing assembly. Environment.UserInteractive is noted as unreliable, you can mess about with WMI and see if the service you expect t be running as is in there and the process id makes sense, but it's a lot of work for an iffy test. The parameter will make degbugging and unit testing for both scenarios easier to possible as well.

Upvotes: 0

Marty
Marty

Reputation: 7522

Have a look at the Environment.UserInteractive property. It should tell you exactly what you want.

Upvotes: 1

Related Questions