3

I want to control a MySQL service from a .NETCore project. I was able to do this in a .NETFramework 4.7 project with a reference to System.ServiceProcess.dll. .NETCore projects seem to use a different System.ServiceProcess.dll which has less functionality.

Is there a different way to control a MySQL service using .NETCore? Can I just reference the .NETFramework dll from a .NETCore project?

user2687412
  • 353
  • 1
  • 3
  • 6
  • You may want to rework the tags... It seems not to be MySQL specific but might apply to any service. It seems .NET Core specific however. – sticky bit Mar 28 '21 at 17:35
  • Is there something special you want to do with the service? If it is just stop/start etc you can look at this link: https://stackoverflow.com/questions/41014513/windows-service-with-net-core, otherwise you need to tell us more about what you want to do with the service – MrApnea Mar 28 '21 at 18:40

2 Answers2

5

I make it work. It's as follows:

  1. Install System.ServiceProcess.ServiceController package using nuget from Visual Studio (Tools > Nuget Package Manager > Manage Nuget Packages for Solution)
  2. Use the following code as example. This link will explain how to use the code: https://learn.microsoft.com/en-us/dotnet/api/system.serviceprocess.servicecontroller.start?view=dotnet-plat-ext-6.0

Check whether the Alerter service is started.

ServiceController sc  = new ServiceController();
sc.ServiceName = "Alerter";
Console.WriteLine("The Alerter service status is currently set to {0}", sc.Status.ToString());

if (sc.Status == ServiceControllerStatus.Stopped)
{
    // Start the service if the current status is stopped.
    
Console.WriteLine("Starting the Alerter service...");
try
{
// Start the service, and wait until its status is "Running".
    sc.Start();
    sc.WaitForStatus(ServiceControllerStatus.Running);

    // Display the current service status.
    Console.WriteLine("The Alerter service status is now set to {0}.", sc.Status.ToString());
 }
 catch (InvalidOperationException)
 {
     Console.WriteLine("Could not start the Alerter service.");
 }
}
  1. You have to open your .exe application using right click > admin privilegies, but the better way is to add a manifest file so when the application open will ask for admin privilegies. you can check how to do that here: How to request administrator permissions when the program starts?
0

What you're looking for is something called a BackgroundService's in Net Core It allows you to run a long running process while the application is running. This should get you started:

https://learn.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-5.0&tabs=visual-studio

Robert Perry
  • 1,906
  • 1
  • 14
  • 14