When you create a Windows Service, you create a list of the services you want to start. The default is this:
ServicesToRun = New System.ServiceProcess.ServiceBase() {New Service}
Can you have multiple instances of the same Service class (that bind to different addresses or ports), like this?
ServicesToRun = New System.ServiceProcess.ServiceBase() {New Service("Option1"), New Service("Option2")}
Or will that cause problems? Should we use two different classes instead? What's the best approach to this problem?
A service by itself doesn't bind to addresses or ports. You can make the service start threads or tasks that do, so one service could start threads for listening to e.g. http and other addresses:ports or whatever you want it to do.
The following example shows you what I mean, it's in C# but if it doesn't translate well to you then use this to translate. My Main function would in your case be the Start function of your service.
public abstract class ServiceModuleBase
{
public abstract void Run();
}
public class SomeServiceModule : ServiceModuleBase
{
//Implement Run for doing some work, binding to addresses, etc.
}
public class Program
{
public static void Main(string[] args)
{
var modules = new List<ServiceModule> {new SomeServiceModule(), new SomeOtherServiceModule()};
var tasks = from mod in modules
select Task.Factory.StartNew(mod.Run, TaskCreationOptions.LongRunning);
Task.WaitAll(tasks.ToArray());
Console.Out.WriteLine("All done");
Console.ReadKey();
}
}
Also, here is a nice summary of why your first approach doesn't work and an alternative way of how to get around that
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With