Dependency injection
Until now, anytime we needed an object inside a class, we passed in the object or we created it in the body of the class. This creates a dependency (the receiving method is dependent on the object passed in or created.) This approach creates tight coupling – which just means that both classes are coupled together and changing one risks having to change the other. For example, in PreferencesViewModel
, we need a PreferenceService
object. The approach we’ve taken so far is to new one up in the constructor:
private readonly PreferenceService service; public PreferencesViewModel() { service = new(); }
Dependency injection decouples the classes and allows for more powerful unit testing, as we’ll see when we continue the discussion of mocks. Rather than newing-up a PreferenceService
, we want to pass in an interface and have .NET MAUI create it for us (that is, no calling function will add the interface to the constructor call –...