简体   繁体   中英

C# - .NET Core Serilog and Appsettings in all classes

I've a question regarding C# and .NET Core. The aim is to create a basic template which allows me to use Serilog as logging service and access app settings in all necessary classes.

Therefore, my Main() methode looks like the following:

        static void Main(string[] args) {

        var builder = new ConfigurationBuilder();
        BuidConfig(builder);

        Log.Logger = new LoggerConfiguration()
            .ReadFrom.Configuration(builder.Build())
            .CreateLogger();

        try {

            Log.Information("Starting...");

            var host = Host.CreateDefaultBuilder()
                .ConfigureServices((conext, services) => {
                    services.AddTransient<IADSyncSvc, ADSyncSvc>();
                })
                .UseSerilog()
                .Build();
            
            var svc = ActivatorUtilities.CreateInstance<ADSyncSvc>(host.Services);
            svc.Run();
        }
        catch (Exception ex) {
            Log.Fatal(ex, "Failed!");
        }
        finally {
            Log.CloseAndFlush();
        }

    }

The builder config will be created in this method:

        static void BuidConfig(IConfigurationBuilder builder) {
        builder.SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
            .AddEnvironmentVariables();
    }

Basically this class is my entry point for my application and executes the Run() method in my ADSyncSvc class. My ADSyncSvc class looks like:

    public class ADSyncSvc : IADSyncSvc {

    private readonly ILogger<ADSyncSvc> _log;
    private readonly IConfiguration _config;
    public ADSyncSvc(ILogger<ADSyncSvc> log, IConfiguration config) {
        this._log = log;
        this._config = config;
    }

    public void Run() {
    }
}

This is working just fine but my problem is to access my Serilog and Appsettings Config which I have written to the appsettings.json file in any other class. What is the best way to achieve this? How should I modify my config to allow other Service classes to access this settings?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM