Im trying to make a dependency injection of Serilog into a solution of multiple projects, so that all projects can use it.
My Entryproject with the Program.cs starts a workerservice
string workingDirectory = AppDomain.CurrentDomain.BaseDirectory;
string logName = "\\ServiceHub_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".log";
string logPathAndName = workingDirectory + logName;
ILogger logger = SetupLogging(logPathAndName);
logger.Information($"Current Working Domain: {workingDirectory}");
ILogger SetupLogging(string logFileName)
{
// Setup Logging
ILogger logger = Log.Logger = new LoggerConfiguration()
.WriteTo.Console(outputTemplate: "[{Timestamp:yyyy-MM-dd HH:mm:ss}] {Level:u3} - {Message:lj}{NewLine}{Exception}")
.WriteTo.File(logFileName, outputTemplate: "[{Timestamp:yyyy-MM-dd HH:mm:ss}] - {Level:u3} {Message:lj}{NewLine}{Exception}")
.CreateLogger();
return logger;
}
try{
using IHost host = Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration(app =>
{
app.AddJsonFile($"appsettings.json");
})
.ConfigureServices((hostContext, services) =>
{
services.AddHostedService<WorkerService>();
services.AddSingleton<IInterface1, Class1>();
services.AddSingleton<IInterface2, Class2>();
})
.UseSerilog()
.Build();
} catch (Exception ex){
{....}
await host.RunAsync();
This is part of one project in the solution. I would like to be able to use the injected Serilog ex. by having the ctor(ILogger logger) in another project which is part of the same solution, but no matter what i do or read, i cannot seem to crack the code. The other projects has got references to this project. But when i instantiate a class, i have to put (New Serilog.Logger) in the parameter list.
I hope this makes sence. Can anybody point me in the right direction ?
Thankyou in advance.
you can register you dependent interface with respective implementation into entry project and inject the interface as dependency into other project. for example create a project where you can define your interface ILogger that would be common for all projects & create an other project LoggerUtility and do implementation of that interface and register this implemented class with respective interface in entry project and inject Ilogger in other project.