I have recently started a small project (C# .Net console application) and I'm trying to use dependency injection "properly" with Castle Windsor as my DI container.
I am not entirely new to dependency injection since I've been unit testing for some time. I feel I've been doing OK so far but have run into a scenario where I feel I must instantiate an object far from the composition root.
In my data access layer I am using the Entity Framework (6) to get data from my database. This is all hidden behind interfaces that are defined in my domain logic layer.
I need to add a new log record, here is an abridged and edited version of my code;
public class Logger:ILogger
{
private readonly IContext _context;
public Logger(IContext context)
{
_context = context;
}
public void Write(string message)
{
var log = new Log();
log.Message = message;
context.Logs.Add(Log);
context.Save();
}
}
Log implements the ILog interface;
public interface ILog
{
string Message { get; set; }
}
This is a solution I have used in the past because it is possible to unit test this code but I am no longer injecting all my dependencies.
I have considered method injection (i.e pass an ILog in with the message), but where would the class that is consuming this code get it's instance from? The same problem is true if I were to inject a factory, it takes the problem out of this class and moves it to another.
I suspect that the solution (if one is required) lies in how I set up the object lifetime of the instances of ILog.
In my real implementation I have a Controller class that takes an instance of ILogger. I can register concrete implementations for Controller, ILogger and IContext with my DI container and I can resolve an instance of Controller and run the application but at run-time I need an unknown number of Log instances.
How can I push the creation of Log instances back to my DI container? Is this something I should be trying to do?