简体   繁体   中英

Advantage of using Dependency Injection when the implementation changes

I'm developing a small Console Application, and I'm logging the transactions.

I applied the DI (Ninject) using the following code:

    class Program
    {
        private static ILogger _logger;        
        private static IKernel kernel;

        static Program()
        {
            kernel = new StandardKernel();
            kernel.Bind<ILogger>().To<Log4NetWrapper().WithConstructorArgument<Type>(MethodBase.GetCurrentMethod().DeclaringType);            
        }

        static void Main(string[] args)
        {
            _logger = kernel.Get<ILogger>();   
            try
            {   
                _logger.Info("Initializing...etc " + i.ToString() + ": " + DateTime.Now);
            }
            //etc...
        }
     }

That works fine, but then I thought using Factory to achieve the same result in another class (for comparison):

public class TestLogFactory
{
    private static readonly ILogger _logger =
         LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

    public void LogInfo(object message)
    {
        _logger.Info(message);
    }
}

The second approach looks cleaner to me, and If i change implementation (replace the log implementation) I only have to change LogManager class, but in the first approach i need to change every class that injects the dependency. My question: is there any advantage when using the first approach in this scenario? I'm learning about DI that's why I'm trying to use it.

Thanks

That's not DI, it's actually a ServiceLocator . Your app is way to trivial to need DI, but in a real app DI means this

class MyClass
{
         public MyClass(ADependency dep1,OtherDependency dep2){}
 }

This means, the deps are injected into the object by a third party (manually or using a DI Container). Usually, these are services which will be automatically invoked by a framework which will use a DI Container as the object factory.

The Di container then inspects the dependencies and their dependencies and then constructs the object with all the required dependencies injected automatically.

A DI Container is a Factory, albeit one that you don't have to write, but only configure. However the objects should be designed to accept the needed dependencies via constructor and those deps should be abstractions. The DI part is the fact that your object doesn't manage the deps but it gets them injected.

When using a DI Container and things change, you'll need to change the container configuration but that's it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM