Sergio
Sergio

Reputation: 2108

DI of a service used by many different ViewModels

I have a ViewManager that I use to manage my Views. It is placed in the App.View namespace and implements an IViewManager interface, placed in the App.ViewModel library.

The problem is that this class is used by many ViewModels, because many of them need to show another View. So I need to ctor-inject the ViewManager in many ViewModels, but some of them need a Factory to be created, so my questions are:

Thank you all for your help!

EDIT

namespace BM.ViewModel
{
    public interface IViewManager
    {
        void Register<TViewInterface, TViewImplementation>(bool reset = false)
            where TViewInterface : IView
            where TViewImplementation : TViewInterface;

        void Unregister<TView>()
            where TView : IView;

        void UnregisterAll();

        TView GetView<TView>(BaseViewModel viewModel)
            where TView : IView;

        IEnumerable<IView> GetViews(BaseViewModel viewModel);

        IEnumerable<IView> GetAllViews();

        void CloseViews<TView>()
            where TView : IView;

        void CloseViews(BaseViewModel viewModel);


        void CloseAllViews();
    }
}

Upvotes: 0

Views: 67

Answers (1)

sll
sll

Reputation: 62544

Everything seems fine, you are injecting dependencies and using factories, these are good practices.

Regarding ViewManager instance, if ViewManager is singleton - it does not matter how to access it - using a factory or any other reference to ViewManager must return the same instance. And I do not see why you should keep many instances of ViewManager, but it depends on your specific application design. So please share IViewManager interface declaration and give some comments for each method so it will be clear whether IViewManager should be a singleton or not.

Some points to concern

  • Is ViewManager stateless?
  • Is there any functionality which obligates ViewManager to keep references to all View instancess?

Upvotes: 1

Related Questions