Am new into using dependency injection and interfaces, and i have run into a situation where i can't figure out how to solve.
Im building a console app, where i need to use serilog, and get settings from the appsettings.json
I have 3 .cs files.
Program.cs:
static void Main(string[] args)
{
Directory.SetCurrentDirectory(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));
var builder = new ConfigurationBuilder();
BuildConfig(builder);
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(builder.Build())
.Enrich.FromLogContext()
.CreateLogger();
Log.Logger.Information("Starting Datacollection");
var host = Host.CreateDefaultBuilder()
.ConfigureServices((context, services) =>
{
services.AddTransient<IMyClass, MyClass>();
})
.UseSerilog()
.Build();
var svcMyClass = ActivatorUtilities.CreateInstance<MyClass>(host.Services);
svcMyClass.MyMethod();
}
IMyClass.cs:
public interface IMyClass
{
void MyMethod();
}
and MyClass.cs:
public class MyClass : IMyClass
{
private readonly ILogger<MyClass> _log;
private readonly IConfiguration _config;
public MyClass(ILogger<MyClass> log, IConfiguration config)
{
_log = log;
_config = config;
}
public void MyMethod()
{
//Do something
}
}
All of this works great. And i can use _log and _config to access Serilog and the config from within MyClass.
However now need to call methods from a new Class (MyClass2) from within MyMethod, and the Methods in MyClass2 needs to be able to use Serilog and the config file.
What is the best way to do this?