MVVM Dependency Injection - MVVM

What is MVVM Dependency Injection?

In this chapter, we can briefly discuss about dependency injection. we have already included information binding decouples views and ViewModels from each different that allows them to speak without knowing explicitly what goes on at the other end of the communique.

Now we want something similar to decouple our ViewModel from the client services.

In early days of object-orientated programming, builders have confronted the problem of making and retrieving times of classes in programs. various solutions had been proposed for this problem.

For the past few years, dependency injection and inversion of control (IoC) have gained recognition among developers and feature taken precedence over some older solutions including the Singleton pattern.

Dependency Injection / IoC Containers

IoC and dependency injection are two layout patterns which can be closely associated and the container is basically a chunk of infrastructure code that does each of those styles for you.

  • IoC sample is ready delegating responsibility for construction and the dependency injection pattern is ready presenting dependencies to an object it's already been constructed.
  • They can each be treated as a -phase approach to constructing. while you use a box, the container takes several responsibilities which are as follows −
    • It constructs an object when asked.
    • The container will decide what that item depends on.
    • Constructing those dependencies.
    • Injecting them into the object being constructed.
    • Recursively doing process.

Let’s have a look at how we will use dependency injection to break decoupling among ViewModels and the client services. we will wire up the save handling AddEditCustomerViewModel shape through using dependency injection related to that.

First we want to create a new interface in our task in services folder. if you don’t have a services folder on your project then create it first and upload the following interface in the services folder.

Following is the implementation of ICustomersRepository.

The simple way to do keep handling is to add a new example of ICustomersRepository in AddEditCustomerViewModel and overload the AddEditCustomerViewModel and CustomerListViewModel constructor.

Update the OnSave method as shown in the following code.

Following is the complete AddEditCustomerViewModel.

When the above code is compiled and done, you may see the same output but now ViewModels are more loosely decoupled.

MVVM – Dependency Injection

When you press the upload customer button, you may see the following view. when the user leaves any subject empty, then it becomes highlighted and the save button becomes disabled.

MVVM – Dependency Injection

All rights reserved © 2020 Wisdom IT Services India Pvt. Ltd Protection Status

MVVM Topics