Cook Computing

Injected Type Needs to Know Type Being Injected Into

March 11, 2009 Written by Charles Cook

Injecting a logger into an object is a frequently used example of DI. I have a case where the logger I want to inject needs to know the type of the object it is being injected into, so that as part of its output it can log the type from which each log line is being output. For example in the code below, where the constructor of type Foo has a parameter of type ILogger and where the implementation of ILogger - the Logger class - has a Type parameter.


class Logger : ILogger
{
    Type _loggerClientType;

    public Logger(Type loggerClientType)
   {
        _loggerClientType = loggerClientType;
   }

    // ...
}

class Foo
{
    ILogger _logger;

    public Foo(ILogger logger)
    {
        _logger = logger;
    }

    // ...
}

I posted to the Unity discussion forum, asking if there any way of achieving this with Unity. Dan Piessens replied:

The short answer is yes, but not without writing some serious Unity extensions. You'd need to override the default parameter and property resolvers, create a resolver that gets and stores the type of the object being resolved and then adds the type into the build stack before resolution then removes it. We got it all working with an set of extensions we wrote, but it's pretty complicated and unfortunately our IP rules don't allow us to release that code.

I replied:

If I get the time I may look into doing something similar to what you have done. For now I have made the ILogger members static and marked them with a custom attribute so that at startup I can scan all the types in the assembly and initialize any attributed ILogger members I find.