使用 CommonServiceLocator 将依赖项注入基类是一个好习惯吗?

发布于 2024-11-03 04:14:03 字数 759 浏览 7 评论 0原文

目前,当我需要将依赖项注入基类时,我使用以下代码:

public class BaseClass
{
    readonly IService _service;
    public BaseClass(IService service)
    {
        _service = service;
    }
}

public class A : BaseClass
{
    public A(IService service) : base(service)
    {
    }
}

public class B : BaseClass
{
    public B(IService service) : base(service)
    {
    }
}

我必须在所有子类中编写大量重复代码。为了避免这些重复的代码,我想我可以使用 CommonServiceLocator 将依赖项注入到基类中:

public class BaseClass
{
    readonly IService _service;
    public BaseClass()
    {
        _service = ServiceLocator.Current.GetInstance<IService>();
    }
}

public class A : BaseClass
{
}

public class B : BaseClass
{
}

这似乎要简单得多,但我不确定这是否是一个好的做法。

谢谢

Currently when I need to inject dependencies into base class, I use the following code:

public class BaseClass
{
    readonly IService _service;
    public BaseClass(IService service)
    {
        _service = service;
    }
}

public class A : BaseClass
{
    public A(IService service) : base(service)
    {
    }
}

public class B : BaseClass
{
    public B(IService service) : base(service)
    {
    }
}

I have to write a lot of duplicate code in all sub classes. To avoid these duplicate code, I think I can use CommonServiceLocator to inject dependencies into the base class:

public class BaseClass
{
    readonly IService _service;
    public BaseClass()
    {
        _service = ServiceLocator.Current.GetInstance<IService>();
    }
}

public class A : BaseClass
{
}

public class B : BaseClass
{
}

This seems to be much simpler, but I'm not sure if this is a good practice.

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

风渺 2024-11-10 04:14:03

从类内请求依赖项称为服务定位器模式,它是一个反模式。防止最大限度地减少应用程序和 IoC 框架之间的依赖性,即使它是公共服务定位器。

我仍然会选择第一种方法,但我同意如果基类总是需要这种依赖关系并且您有许多子类型,那么这可能会变得很麻烦。在这种情况下,请进行属性注入:

public class BaseClass
{
    public BaseClass()
    {
    }

    public IService Service { get; set; }
}

这样您的库就可以免于使用服务定位器。对我来说,这种方法的最大优点之一是它使编写单元测试变得不那么痛苦。

Requesting a dependency from within a class is called the Service Locator Pattern, which is an anti-pattern. Prevent to minimize the dependency between your application and the IoC framework, even if it is the Common Service Locator.

I would still go for the first approach, but I agree that if the base class always needs that dependency and you have many sub types, this can become cumbersome. In that case, go for property injection:

public class BaseClass
{
    public BaseClass()
    {
    }

    public IService Service { get; set; }
}

This way your library is free from using a Service Locator. One of the greatest advantages of this approach for me, is that it makes writing unit tests much less painful.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文