Is it a good practise to use CommonServiceLocator to inject dependencies into base class?
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 dup开发者_如何学Clicate 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
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.
精彩评论