Suppose I have an interface for a service:
public interface IFooService
{
void DoSomething();
}
And a concrete implementation of that service that is a generic:
public class FooService<TRequestingClass> : IFooService
{
public virtual void DoSomething() { }
}
And I have some other class that needs an instance of IFooService:
public class Bar
{
private IFooService _fooService;
public Bar(IFooService fooService)
{
this._fooService = fooService;
}
}
I need to wire up my IoC container such that when Bar gets created, it gets passed a constructor argument of FooService<Bar>. There are many other classes just like Bar. Each might also need an instance of FooService<TRequestingClass> passed to them where TRequestingClass is the type of the class that needs the instance of IFooService. I don't need to expose this quirkiness to the consumers of IFooService. All they should care about is that they can call the methods of the IFooService they were passed. They should not need to know that the concrete implementation of IFooService they were passed needed anything special to be constructed.
An acceptable alternatative to FooService<T> would to be a non-generic class that has a string argument in its constructur that contains the name of the class it is being created for. i.e:
public class FooService : IFooService
{
public FooService(string requestingClassName) { }
}
How can I wire up my IoC container to construct a dependency this way?
If you are confused why I would want such a wierd structure, consider how log4net works best when you get an ILog that gets created with log4net.LogManager.GetLogger(typeof(SomeClass)). I don't want to litter my code with references to log4net, so I'd like to write a simple ILogger interface, and implement it with something like this:
public class GenericLogger<T> : ILogger
{
private readonly ILog log;
public GenericLogger()
{
this.log = log4net.LogManager.GetLogger(typeof(T));
}
public void Debug(object message)
{
this.log.Debug(message);
}
/* .... etc .... */
}