This project is read-only.

Context Based Injection with Constructor Parameter

Jan 1, 2014 at 11:27 PM
I'm very new to Simple Injector, and as a first step I wanted to try implementing a simple logging interface with NLog as the implementation. Here's a simplified outline of my code:
public interface ILogger
    {    
        void Info(string message);
    }

public class NLogLogger: ILogger
    {
        private Logger logger;
        
        public NLogLogger(string source)
        {
            logger = LogManager.GetLogger(source);
        }

        public void Info(string message)
        {
            logger.Info(message);
        }
    }
In this case, the source parameter in the NLogLogger constructor would be the name of the class that's using the logger (e.g. "MyClass1", "MyClass2").

I've come to understand that having an argument in the constructor of my implementation involves context based injection and that Simple Injector was created with certain design goals in mind which shape the usage of this feature. Here are a few discussions that I've tried to learn from:

How to return an instance based on its parent using Simple Injector?
Simple Injector: Registering a type with constructor argument that's based on its parent
Specify contructor arguments
Register an Interface wich implementation's constructor has arguments


So, in order to make this work, I inserted the following code in the InitializeContainer() method:
container.RegisterWithContext<ILogger>(context => { return new NLogLogger(context.ImplementationType.Name); });
However, upon execution, an exception was thrown because context.ImplementationType was null. Noticing that the problem seemed to be with the call to container.Verify(), I consulted the following discussion:

Context based injection and .Verify()

The example in that discussion doesn't demonstrate how to pass in constructor parameters, though (unless I'm just missing it).

In the end, I guess I'm just looking for a really basic explanation of how to make this kind of context based injection work. Any suggestions or code samples would definitely be appreciated.

As an aside, I would eventually like to implement this log injection in an MVC5 project. The logging will be for diagnostic and historical purposes only - exception and error logging will be handled by a separate module. Given the advice here, is it possible that I'm overlooking a more simple and elegant way of implementing this logging feature, or is injecting the logger into the constructor of an MVC controller still viewed favorably?

Thanks for the help, and for taking the time to support this project.
Coordinator
Jan 2, 2014 at 6:02 AM
Edited Mar 2, 2014 at 7:18 PM
There's an issue report that describes what you are seeing and how to solve it:

https://simpleinjector.codeplex.com/workitem/20571
Marked as answer by dot_NET_Junkie on 3/2/2014 at 11:18 AM