1

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:

  1. ItemsListViewModel has a reference to IService and it can use this reference to create instances of ItemViewModel.
  2. 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
  3. 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:

  1. 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.
  2. In this case we need to have another level of unnecessary abstraction (some class creates another class in an abstract way).
  3. 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?

1

I would go with 2, the abstraction is not unnecessary if you need to create a an instance determined at runtime and keep it loosely coupled.

The problem with 3 is that you're coupling ItemViewModel to the DI container.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.