I have the following problem: I am coding a Windows service using a console app project and Topshelf nuget . I am using Unity container to implement DI. Additionally, I would like to log the Windows events (through Event Viewer) and the AppInsights service. All of that by using Microsoft's ILogger. Here is some sample:
using System;
using Topshelf;
using Unity;
using Unity.Lifetime;
using Topshelf.Unity;
using Microsoft.Extensions.Logging;
namespace WindowsServiceExample
{
public class Program
{
static void Main(string[] args)
{
var container = new UnityContainer();
container.RegisterType<IExamplaryService, ExamplaryService>(new ContainerControlledLifetimeManager());
container.RegisterType<IAppInsightsService, AppInsightsService>(new ContainerControlledLifetimeManager());
container.RegisterType<IEventLogService, EventLogService>(new ContainerControlledLifetimeManager());
//two following lines i'm not sure
container.RegisterInstance<ILoggerFactory>(new LoggerFactory());
container.RegisterSingleton(typeof(ILogger<>), typeof(Logger<>));
TopshelfExitCode exitCode = HostFactory.Run(hostConfigurator =>
{
hostConfigurator.UseUnityContainer(container);
hostConfigurator.Service<IExamplaryService>(serviceConfigurator =>
{
serviceConfigurator.ConstructUsingUnityContainer();
serviceConfigurator.WhenStarted(service => service.Start());
serviceConfigurator.WhenStopped(service => service.Stop());
});
hostConfigurator.RunAsLocalSystem();
hostConfigurator.StartAutomatically();
hostConfigurator.SetServiceName("ExamplaryService");
hostConfigurator.SetDisplayName("Examplary Service");
hostConfigurator.SetDescription("Description of Examplary Service.");
hostConfigurator.EnableShutdown();
hostConfigurator.EnablePauseAndContinue();
});
int exitCodeValue = (int)Convert.ChangeType(exitCode, exitCode.GetTypeCode());
Environment.ExitCode = exitCodeValue;
}
}
}
And here I have a problem: how to properly connect ILogger with Unity? How to tell the Logger that I want to log stuff from AppInsights and Windows events?
As a final result I'd like to use:
_logger.LogInformation("some info")
and get it logged to AppInsights and Windows Event log.