服务定位器和依赖项注入之间的实际区别是什么? [英] What is the actual difference betwen a service locatior and a dependency injection?

查看:76
本文介绍了服务定位器和依赖项注入之间的实际区别是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在遍历之前的讨论,其中对服务定位器和依赖项注入器之间的区别进行了详细讨论,但仍然无法理解。
我可以在没有任何代码的情况下获得一般答复吗?

I was going through the previous discussion in which there was a detailed discussion on the difference between a service locator and a dependency injector, but still I am not able to get that. Can I get a general response without any code?

推荐答案

此代码示例应用了依赖注入原理:

This code sample applies the Dependency Injection principle:

public class UserService : IUserService
{
    private IUserRepository repository;

    // Constructor taking dependencies
    public UserService(IUserRepository repository)
    {
        this.repository = repository;
    }
}

此代码示例使用服务定位器模式:

public class UserService : IUserService
{
    private IUserRepository repository;

    public UserService()
    {
        this.repository = ObjectFactory.GetInstance<IUserRepository>();
    }
}

这是Service Locator模式的实现:

And this is an implementation of the Service Locator pattern:

public class UserService : IUserService
{
    private IUserRepository repository;

    public UserService(Container container)
    {
        this.repository = container.GetInstance<IUserRepository>();
    }
}

这甚至是Service Locator模式的实现:

And even this is an implementation of the Service Locator pattern:

public class UserService : IUserService
{
    private IUserRepository repository;

    public UserService(IServiceLocator locator)
    {
        this.repository = locator.GetInstance<IUserRepository>();
    }
}

不同之处在于,依赖注入使您全部注入消费者需要的依赖关系,进入消费者(但除此之外)。注入它的理想方法是通过构造函数。

The difference is that with Dependency Injection, you inject all dependencies a consumer needs, into the consumer (but nothing else). The ideal way of injecting it is through the constructor.

使用Service Locator,您可以从某些共享源请求依赖项。在第一个示例中,这是静态 ObjectFactory 类,而在第二个示例中,这是注入的 Container 实例进入构造函数。尽管容器本身是使用依赖项注入来注入的,但是最后一个代码片段仍是Service Locator模式的实现。

With Service Locator you request the dependencies from some shared source. In the first example this was the static ObjectFactory class, while in the second example this was the Container instance that was injected into the constructor. The last code snippet is still an implementation of the Service Locator pattern, although the container itself is injected using dependency injection.

出于重要原因,您应该对依赖项使用服务定位器。 这篇文章很好地解释了它

There are important reasons why you should use Dependency Injection over Service Locator. This article does a good job explaining it.

这篇关于服务定位器和依赖项注入之间的实际区别是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆