Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVVM with Unity and Unit Testing architectural design

I'm building a Visual Studio-like application in WPF and I'm having some problems identifying the best architectural design organization of my components. I plan to use Unity as my dependency-injection container and Visual Studio Unit Testing framework and probably moq for mocking library.

I'll first describe the structure of my solution, then my questions:

I have a WPF project that contains:

  • My Unity container initialization (bootstrapper) on application startup (in App.xaml.cs)
  • All my application Views (XAML).

Another project called ViewModel this contains:

  • All my application ViewModels. All my ViewModels inherit from a ViewModelBase which exposes a ILogger property

My initialization logic is as follows:

  1. Application Startup
  2. Unity container creation and registration of types: MainView and MainViewModel
  3. Resolve my MainView and show it.

var window = Container.Resolve<MainView>();

window.Show();

My MainView constructor receives a MainViewModel object in its constructor:

public MainView(MainViewModel _mvm)
  1. My MainViewModel has a Child ViewModel for each of its panels:

    public ToolboxViewModel ToolboxVM{get; set;}
    public SolutionExplorerViewModel SolutionExplorerVM { get; set; }
    public PropertiesViewModel PropertiesVM { get; set; }
    public MessagesViewModel MessagesVM { get; set; }
    

And I'm planning to create a InitializePanels() method that initializes each of the panels.

Now here my questions: How can my MainViewModel.InitializePanels() initialize all those panels? given the following options:

Option 1: Initialize the ViewModels manually:

ToolboxVM = new ToolboxViewModel();
//Same for the rest of VM...

Cons:

  • I'm not using the Unity container so my dependencies (e.g. ILogger) are not automatically resolved

Option 2: Use setter injection by annotating my properties:

[Dependency]
public ToolboxViewModel ToolboxVM{get; set;}
//... Same for rest of Panel VM's

Cons:

  • I've read that Unity Setter dependencies should be avoided since they generate a dependency with Unity in this case
  • I've also read that you should avoid using Unity for Unit Tests, so how to make this dependency clear in my Unit Tests? Having many dependent properties could be a nightmare to configure.

Option 3: Use Unity Constructor injection to pass ALL my Panel ViewModels to the MainViewModel constructor so they are automatically resolved by Unity container:

public MainViewModel(ToolboxViewModel _tbvm, SolutionExploerViewModel _sevm,....)

Pros:

  • The dependency would be evident and clear at time of creation, which could help building my ViewModel UnitTests.

Cons:

  • Having so many constructor parameters could get ugly pretty quickly

Option 4: Registering all my VM types at container buildup. Then passing the UnityContainer instance through constructor injection to my MainViewModel:

public MainViewModel(IUnityContainer _container)

That way I could do something like:

        Toolbox = _container.Resolve<ToolboxViewModel>();
        SolutionExplorer = _container.Resolve<SolutionExplorerViewModel>();
        Properties = _container.Resolve<PropertiesViewModel>();
        Messages = _container.Resolve<MessagesViewModel>();

Cons:

  • If I decide NOT to use Unity for my UnitTests, as many people suggest,then I won't be able to resolve and initialize my Panel ViewModels.

Given that lengthy explanation, what is the best approach so that I can take advantage of a Dependency Injection Container and end up with a Unit-Testable solution??

Thanks in advance,

like image 611
Adolfo Perez Avatar asked Jun 22 '12 14:06

Adolfo Perez


3 Answers

First things first... As you noticed, your current setup might be problematic when unit testing (complex VM initialization). However, simply following DI principle, depend on abstractions, not on concretions, makes this problem go away immediately. If your view models would implement interfaces and dependencies would be realized through interfaces, any complex initialization becomes irrelevant as in test you'll simply use mocks.

Next, problem with annotated properties is that you create high coupling between your view model and Unity (this is why it is most likely wrong). Ideally, registrations should be handled at single, top level point (which is bootstrapper in your case), so container is not bound in any ways to object it provides. Your options #3 and #4 are most common solutions for this problem, with few notes:

  • to #3: too many constructor dependencies is usually mitigated by grouping common functionality in facade classes (however 4 is not that many after all). Usually, properly designed code doesn't have this problem. Note that depending on what your MainViewModel does maybe all you need is dependency to list of child view models, not concrete ones.
  • to #4: you shouldn't use IoC container in unit tests. You simple create your MainViewModel (via ctor) manually and inject mocks by hand.

I'd like to address one more point. Consider what happens when your project grows. Packing all view models into single project might not be good idea. Each view model will have its own (often unrelated to others) dependencies, and all this stuff will have to sit together. This might quickly become difficult to maintain. Instead, think whether you can extract some common functionalities (for example messaging, tools) and have them in separate groups of projects (again, split into M-VM-V projects).

Also, it's much easier to swap views when you have functionality related grouping. If project structure looks like this:

> MyApp.Users
> MyApp.Users.ViewModels
> MyApp.Users.Views
> ...

Trying out different view for user edit window is a matter of recompiling and swapping single assembly (User.Views). With all in one bag approach, you'll have to rebuild much larger part of application, even tho majority of it haven't changed at all.

Edit: keep in mind that changing existing structure of project (even tiny one), is usually a very costly process with minor/none business results. You might not be allowed or simply not be able to afford doing so. Usage-based (DAL, BLL, BO, etc) structure does work, it just gets heavier with time. You can just as well use mixed mode, with core functionalities grouped by their usage and simply adding new functionalities utilizing modular approach.

like image 126
k.m Avatar answered Nov 15 '22 21:11

k.m


First off, you'd probably want to use interfaces rather than concrete classes, so that you'll be able to pass you mock objects when unit testing, i.e IToolboxViewModel instead of ToolboxViewModel, etc.

That being said, I would recommend the third option - constructor injection. This makes the most sense, since otherwise you could call var mainVM = new MainViewModel() and end up with a non-functional view model. By doing that, you're also making it very easy to understand what are your view-model's dependencies, which makes it easier to write unit tests.

I would check out this link, as it's relevant to your question.

like image 31
Adi Lester Avatar answered Nov 15 '22 20:11

Adi Lester


I agree with Lester's points but wanted to add a few other options and opinions.

Where you are passing the ViewModel to the View through the constructor, this is a bit unconventional as WPF's binding capability allows you to completely decouple the ViewModel from the View by binding to the DataContext object. In the design you've outlined, the View is coupled to a concrete implementation and limits reuse.

While a service facade will simplify option 3, it is not uncommon (as you've outlined) for top-level ViewModels to have a lot of responsibilities. Another pattern you can consider is a controller or factory pattern that assembles the viewmodel. The factory can be be backed by the container to do the work but the container is abstracted away from the caller. A key goal in building container-driven apps is to limit the number of classes that understand how the system is assembled.

Another concern is the amount of responsibilities and object relationships that belong to the top-level viewmodel. If you look at Prism (a good candidate with WPF + Unity) it introduces the concept of "regions" that are populated by modules. A region may represent a toolbar which is populated by mutliple modules. Under such a design, the top-level viewmodel has fewer responsibilities (and dependencies!) and each module contains Unit-testable DI components. Big shift in thinking from the example you've provided.

Regarding option 4, where the container is passed in through the constructor is technically dependency inversion but it's in the form of service location instead of dependency injection. Having gone down this path before I can tell you it's a very slippery slope (more like a cliff): Dependencies are hidden inside classes and your code becomes a web of "just in time" madness -- completely unpredictable, totally untestable.

like image 31
bryanbcook Avatar answered Nov 15 '22 19:11

bryanbcook