3

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

vossad01
  • 11,552
  • 8
  • 56
  • 109
  • short answer: no, don't use service locator. there is no duplicate code here. – Mauricio Scheffer Apr 20 '11 at 22:51
  • @Mauricio Scheffer: No duplicate code? I have to put `(IService service) : base(service)` in the constructor of all sub classes. Sometimes the only reason I create a constructor for a subclass is for injecting dependencies into the base class. –  Apr 20 '11 at 23:05
  • ... and that's what you should continue to do. – Johann Gerell Apr 20 '11 at 23:11

1 Answers1

5

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.

Steven
  • 166,672
  • 24
  • 332
  • 435
  • After read your answer, I decide to use property injection for the BaseViewModel and other base classes that have many subclasses. That saved a lot of code. Thanks for your answer and the links! –  Apr 21 '11 at 12:14