Injected Type Needs to Know Type Being Injected Into

Mar 5, 2009 at 10:32 AM
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 contructor of type Foo has a parameter of type ILogger and where the implementation of ILogger - the Logger class - has a Type parameter. Is there any way of achieving this with Unity?

Thanks, Charles

class Logger : ILogger
{
    Type _loggerClientType;

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

    // ...
}

class Foo
{
    ILogger _logger;

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

    // ...
}




Mar 5, 2009 at 1:33 PM
Hi Charles,

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.

-Dan
Mar 6, 2009 at 9:59 AM
Hi Dan: thanks for the reply. 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.

:Charles