× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

Can an abstract class constructor instantiate a new object?

James Jensen
Feb 10, 2015
<p>Jon Skeet (as usual) is correct--you <em>can</em> do this. However, since you're following a Dependency Injection pattern with your child controllers, you should probably use dependency injection for your parent class as well. </p> <p>You can do this by injecting the dependency into the parent's constructor, but as you've probably noticed that requires all the child classes to inject the same object and do a pass-through, which can get annoying as you add more dependencies.</p> <p>Alternatively, you can do Property Injection, but this can make it easy to forget to update unit tests with new properties that need to be injected.</p> <p>As a compromise, I'll often use Method injection, where the base class has an "InjectDependencies" method that initializes the dependencies. Unfortunately, this disallows you from making your dependencies read-only, and still makes it possible to construct your object without providing dependencies.</p> <p>A final option would be to create a special class just for containing the parent class's dependencies, and then inject <em>that</em> class into the parent class's constructor. Child classes then need only pass through a single parameter into the parent constructor, and you're free to add dependencies in the future, which will not affect the child classes, but will alert unit tests that try to construct the dependency object by hand.</p> <p>You should also think carefully about whether you're using inheritance in a situation where you should be using composition. Is <code>MyFirstSharedMethodForAllServices()</code> just a convenience method that you happen to know that several services will use? Why not just create a separate class with this method, which all of those services can inject? This would give you more flexibility, for example, to unit test <code>MyFirstSharedMethodForAllServices()</code> independently. It also leaves your services free to extend some other class based on a more "is a"-style relationship.</p> <p>This tip was originally posted on <a href="http://stackoverflow.com/questions/24540081/Can%20an%20abstract%20class%20constructor%20instantiate%20a%20new%20object?/24540152">Stack Overflow</a>.</p>
comments powered by Disqus