I have an abstract class, Shape, and I have a Canvas object that the Shape uses to set its position. I need to make sure that all Shapes have a Canvas object, preferably a Canvas object that is the same one across all shapes.
I have thought of a couple of options:
-
Add a canvas parameter to the Shape constructors (there are many)
-
Having some sort of place where the abstract Shape gets its Canvas (when a default is required)
-
Make all my shape construction go through a factory of some sort.
Which one is the best?
I am using C# / .NET 3.5
For Dependency Injection (DI) the best default pattern is Constructor Injection (your first option) because it can easily be implemented to ensure your Shapes’ invariants.
Just add a Guard Clause to your Shape ctor like this:
This ensures that the canvas field is always available and never null.
You can achieve this property in other ways, but Constructo Injection is by far the simplest way to ensure invariants, so I always choose that as my default DI strategy unless I have other needs.