Assume I have a class like this:
public interface IService
{
// Gets some data, possibly from a website / database
List<string> GetStrings();
}
public class ItemViewModel : BaseViewModel
{
// Some view-related data...
// Dependency
private readonly IService _service;
// Property to which we bind something in the view that needs to have dynamic up-to-date data, for example, a combo box
public List<string> Strings => _service.GetStrings();
// Constructor injection
public ItemViewModel(IService service)
{
_service = service;
}
}
Let's assume we need to have a list of these view models -- for instance let's have a class ItemsListViewModel
, which takes care of these models, fills their data, removes them if needed, etc. How will this class create them?
I can think of 3 solutions how to deal with it:
ItemsListViewModel
has a reference toIService
and it can use this reference to create instances ofItemViewModel
.ItemsListViewModel
has a reference to an abstract factory that communicates with the DI container and creates the instances. I mean this: https://github.com/ninject/Ninject.Extensions.Factory/wiki/Factory-interface- Changing
ItemViewModel
to:
public class ItemViewModel : BaseViewModel
{
// Some view-related data...
// Dependency
private readonly IService _service;
// Property to which we bind something in the view that needs to have dynamic up-to-date data, for example, a combo box
public List<string> Strings => ServiceLocator.Get<IService>().GetStrings();
}
My opinion on these solutions:
- In this case a class has a dependency that doesn't actually need for anything but passing it further. This approach could lead to a super-class that has all the references and does nothing with them but passing them down.
- In this case we need to have another level of unnecessary abstraction (some class creates another class in an abstract way).
- No need for another abstraction, both classes have readable straightforward code. This seems like the best solution to me.
How would you solve this? Is there 'the best' solution?