使用 CommonServiceLocator 将依赖项注入基类是一个好习惯吗?
目前,当我需要将依赖项注入基类时,我使用以下代码:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
从类内请求依赖项称为服务定位器模式,它是一个反模式。防止最大限度地减少应用程序和 IoC 框架之间的依赖性,即使它是公共服务定位器。
我仍然会选择第一种方法,但我同意如果基类总是需要这种依赖关系并且您有许多子类型,那么这可能会变得很麻烦。在这种情况下,请进行属性注入:
这样您的库就可以免于使用服务定位器。对我来说,这种方法的最大优点之一是它使编写单元测试变得不那么痛苦。
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:
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.