Ashwin Nagarajan
Ashwin Nagarajan

Reputation: 219

Ideal number of Object Instances to pass Via View Model constructor (dependency injection)

I am implementing a project, main objective is to have loosely coupled class implementations, for example below, i am using simple IOC container to inject PageNavigation and AppConfig instance into the view model.

public MyViewModel(IPageNavigationService PageNavigation, IAppConfig AppConfig) {
   //my code
}
  1. is there a limit to number of instances i can pass via constructor? , which may cause unforeseen problems .
  2. what if i would have 5 to 6 object instances i need to pass, is there any other way i can access the object instance other than constructor, keeping things loosely coupled and dynamic, and all View model's using default instance (singleton ) of the object being passed.

Upvotes: 2

Views: 159

Answers (1)

Jehof
Jehof

Reputation: 35544

There is no limit of instances to pass to your viewmodel instance via a constructor. You should pass all dependencies, that are required for your ViewModel to work properly via the constructor.

Dependencies that are optional or providing a diffrent implementation can be passed by PropertyInjection.

You could also define a constructor to get a reference to the IOC-Container, so that the ViewModel resolves the necessary dependencies by itself in the constructor. But then has your viewmodel a dependency to the container what is not required sometimes.

public MyViewModel(IocContainer container) {
   // resolve dependencies via the container
}

Upvotes: 1

Related Questions