I am designing a class that uses an abstract property to provide a point of access to a field. Here is a snippet of my code:
public abstract class PageBroker : WebBroker
{
public abstract IPageProvider Provider { get; }
}
public class ArticleBroker : PageBroker
{
public override IPageProvider Provider { get; } = new ArticleProvider();
}
I realized I could refactor this to use DI instead, like so:
public class PageBroker : WebBroker
{
public PageBroker(IPageProvider provider)
{
this.Provider = provider;
}
public IPageProvider Provider { get; private set; }
// implementation...
}
// no derived class, just new PageBroker(new ArticleProvider())
In what situation(s) would one technique be appropriate over the other?
I agree with BJ Safdie's answer.
That said, I think the main difference is that in the first implementation, ArticleBroker is coupled to a specific implementation of IPageProvider (namely ArticleProvider). If this is intended, I see no problem with it. However, if you want to provide an implementation of IPageProvider at runtime (either in production code or in a unit test via mocks/fakes), then injecting the dependency is the better choice.