Dependency Injection best practices RRS feed

  • Question

  • Hello,

    I am quite new to DI, IOC and TDD. In my project, I'm using Microsoft Unity Block as IOC. I have following scnerio:



        class Program
            static void Main(string[] args)
                UnityContainer container = new UnityContainer();
                UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
                ILogger logger = container.Resolve<ILogger>();
                MyImplementation caller = new MyImplementation (logger);
    class MyImplementation 
            private ILogger _logger;
    	public MyImplementation() { _logger = container.Resolve<ILogger>(); } //constructor 1
            public MyImplementation (ILogger logger) //constructor 2
                _logger = logger;
            public void Execute()
                _logger.Log("Executing transaction");

    Now my question is in MyImplementation, what is the best way to initialize dependency (ILogger) in this case? Should it be like constructor 1 where constructor itself will going to call IOC to resolve the dependency? or is it the responsiblity of caller to resolve the dependency and inject it through constructor or property (constructor 2).

    Most of the example I've seen is using Constructor 1 approch. But I'm confused if I'd use that approct then how am I going to unit test my code? I would not be able to take advantage of Mocking frameworks because my constructor needs to call IOC container to resolve dependency no?


    Please let me know whats the best practice. I would really appreciate your help.





    Tuesday, October 18, 2011 2:40 PM