Dependency Injection vs Service Location

前端 未结 11 1367
梦如初夏
梦如初夏 2020-11-28 03:59

I am currently weighing up the advantages and disadvantages between DI and SL. However, I have found myself in the following catch 22 which implies that I should just use SL

11条回答
  •  遥遥无期
    2020-11-28 04:41

    I know this question is a little old, I just thought I would give my input.

    In reality, 9 times out of 10 you really don't need SL and should rely on DI. However, there are some cases where you should use SL. One area that I find myself using SL (or a variation, thereof) is in game development.

    Another advantage of SL (in my opinion) is the ability to pass around internal classes.

    Below is an example:

    internal sealed class SomeClass : ISomeClass
    {
        internal SomeClass()
        {
            // Add the service to the locator
            ServiceLocator.Instance.AddService(this);
        }
    
        // Maybe remove of service within finalizer or dispose method if needed.
    
        internal void SomeMethod()
        {
            Console.WriteLine("The user of my library doesn't know I'm doing this, let's keep it a secret");
        }
    }
    
    public sealed class SomeOtherClass
    {
        private ISomeClass someClass;
    
        public SomeOtherClass()
        {
            // Get the service and call a method
            someClass = ServiceLocator.Instance.GetService();
            someClass.SomeMethod();
        }
    }
    

    As you can see, the user of the library has no idea this method was called, because we didn't DI, not that we'd be able to anyways.

提交回复
热议问题