Dependency injection between projects in a solution

875 Views Asked by At

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.

2

There are 2 best solutions below

0
Rohit Kumar Mishra On

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.

0
JonasH On

DI does not really know or care about projects. It only cares about classes.

You should be able to resolve other classes that depend on the ILogger interface from the container. But Dependency injection containers are not magic, you need to use the container whenever you need to create objects. For example:

public class MyClass
{
    private readonly ILogger logger;
    public MyClass(ILogger logger) => this.logger = logger;
}
...
var serviceCollection = new ServiceCollection();
serviceCollection.AddSingleton(SetupLogging("test"));
serviceCollection.AddTransient<MyClass>();
var container = serviceCollection.BuildServiceProvider();
var myObj = container.GetService<MyClass>();

Where multiple projects may make things more complicated is when the number of classes start to creep up. Eventually you may want to move the registrations of classes to each project, or create some type of 'Module' with some larger grouping of functionality. Some unit testing might also be useful, in my experience a common problem is that some project forgets to register a dependency. Detecting such problems as early as possible can be useful.