Search code examples
c#wcfserilogapp-code

Serilog WCF usage without constructors?


I am new to c# and I am trying to using serilog in a WCF application. This WCF application is hosted on IIS 6.0.

I need to create the logger once only when the service is initialized. However WCF does not seem to have constructors. How can I create the logger below once only and have it available to the rest of the application. Any code examples would be greatly appreciated.

ILogger logger = new LoggerConfiguration()
                      .ReadAppSettings()
                      .CreateLogger();
              Log.Logger = logger;

I thought about using the AppInitialize in the App_Code folder but I cannot seem to get the program to trigger the AppInitialize method.

public class InitializeApp
{
    public static void AppInitialize()
    {
       
ILogger logger = new LoggerConfiguration()
                      .ReadAppSettings()
                      .CreateLogger();
              Log.Logger = logger;
    } 
}

When I run the project in Visual Studio 2019 AppInitialize never gets hit.


Solution

  • First, you can do the constructor with WCF Service via some Dependency Inject library which supports WCF Service

    You can use AutoFac.WCF then you can register type of ILogger by Autofac

    builder.Register<ILogger>((c, p) =>
    {
        return new LoggerConfiguration()
                     .ReadAppSettings()
                     .CreateLogger();
    }).SingleInstance();
    

    Second, About the "InitializeApp" of the application. there are couple ways to do it.

    1. Add Global.asax file and then you can write the code in Application_Start
    2. Use Owin Middleware to write own pipeline. You can write your code in Startup.cs
    3. Use WebActivator, you can write PreApplicationStartMethod and PostApplicationStartMethod (extension for Global.asax)