The problem is moving from the ServiceLocator anti-pattern to Dependency Injection. In view of my inexperience, I can't shift the DI principle to the code implemented now.
Summary
The Summary section is optional for read. You may want to comment on something, advise.
The main purpose of the program is the process of merging placeholder fields of specific information. Number of information makes need to have infrastructure around. Such as forms, services, database. I have some experience with this task. I managed to create a similar program based on WinForms. And it even works! But in terms of patterns, maintenance, extensibility, and performance, the code is terrible. It is important to understand that programming is a hobby. It is not the main education or job.
The experience of implementing the described task on WinForms is terrible. I started studying patterns and new platform. The starting point is UWP and MVVM. It should be noted that the binding mechanism is amazing.
The first problem on the way was solved independently. It is related to navigation in the UWP via the NavigationView located in the ShellPage connected with ShellViewModel. Along with creating a NavigationService. It is based on templates from Windows Template Studio.
Since there is a working WinForms program and its anti-pattern orientation, there is time and a desire to do everything correctly.
Now I'm facing an architecture problem. Called ServiceLocator (or ViewModelLocator). I find it in examples from Microsoft, including templates from Windows Template Studio. And in doing so, I fall back into the anti-pattern trap. As stated above, I don't want this again.
And the first thing that comes as a solution is dependency injection. In view of my inexperience, I can't shift the DI principle to the code implemented now.
Current implementation
The start point of app UWP is app.xaml.cs. The whole point is to transfer control to ActivationService. Its task is adding Frame to Window.Current.Content and navigated to default page - MainPage. Microsoft documentation.
The ViewModelLocator is a singleton. The first call to its property will call constructor.
private static ViewModelLocator _current;
public static ViewModelLocator Current => _current ?? (_current = new ViewModelLocator());
// Constructor
private ViewModelLocator(){...}
Using ViewModelLocator with View (Page) is like this, ShellPage:
private ShellViewModel ViewModel => ViewModelLocator.Current.ShellViewModel;
Using ViewModelLocator with ViewModel is similar, ShellViewModel:
private static NavigationService NavigationService => ViewModelLocator.Current.NavigationService;
Moving to DI
ShellViewModel has NavigationService from ViewModelLocator as shown above. How can I go to DI at this point? In fact, the program is small. And now is a good time to get away from anti-patterns.
Code
ViewModelLocator
private static ViewModelLocator _current;
public static ViewModelLocator Current => _current ?? (_current = new ViewModelLocator());
private ViewModelLocator()
{
// Services
SimpleIoc.Default.Register<NavigationService>();
// ViewModels and NavigationService items
Register<ShellViewModel, ShellPage>();
Register<MainViewModel, MainPage>();
Register<SettingsViewModel, SettingsPage>();
}
private void Register<TViewModel, TView>()
where TViewModel : class
where TView : Page
{
SimpleIoc.Default.Register<TViewModel>();
NavigationService.Register<TViewModel, TView>();
}
public ShellViewModel ShellViewModel => SimpleIoc.Default.GetInstance<ShellViewModel>();
public MainViewModel MainViewModel => SimpleIoc.Default.GetInstance<MainViewModel>();
public SettingsViewModel SettingsViewModel => SimpleIoc.Default.GetInstance<SettingsViewModel>();
public NavigationService NavigationService => SimpleIoc.Default.GetInstance<NavigationService>();
ShellPage : Page
private ShellViewModel ViewModel => ViewModelLocator.Current.ShellViewModel;
public ShellPage()
{
InitializeComponent();
// shellFrame and navigationView from XAML
ViewModel.Initialize(shellFrame, navigationView);
}
ShellViewModel : ViewModelBase
private bool _isBackEnabled;
private NavigationView _navigationView;
private NavigationViewItem _selected;
private ICommand _itemInvokedCommand;
public ICommand ItemInvokedCommand => _itemInvokedCommand ?? (_itemInvokedCommand = new RelayCommand<NavigationViewItemInvokedEventArgs>(OnItemInvoked));
private static NavigationService NavigationService => ViewModelLocator.Current.NavigationService;
public bool IsBackEnabled
{
get => _isBackEnabled;
set => Set(ref _isBackEnabled, value);
}
public NavigationViewItem Selected
{
get => _selected;
set => Set(ref _selected, value);
}
public void Initialize(Frame frame, NavigationView navigationView)
{
_navigationView = navigationView;
_navigationView.BackRequested += OnBackRequested;
NavigationService.Frame = frame;
NavigationService.Navigated += Frame_Navigated;
NavigationService.NavigationFailed += Frame_NavigationFailed;
}
private void OnItemInvoked(NavigationViewItemInvokedEventArgs args)
{
if (args.IsSettingsInvoked)
{
NavigationService.Navigate(typeof(SettingsViewModel));
return;
}
var item = _navigationView.MenuItems.OfType<NavigationViewItem>().First(menuItem => (string)menuItem.Content == (string)args.InvokedItem);
var pageKey = GetPageKey(item);
NavigationService.Navigate(pageKey);
}
private void OnBackRequested(NavigationView sender, NavigationViewBackRequestedEventArgs args)
{
NavigationService.GoBack();
}
private void Frame_Navigated(object sender, NavigationEventArgs e)
{
IsBackEnabled = NavigationService.CanGoBack;
if (e.SourcePageType == typeof(SettingsPage))
{
Selected = _navigationView.SettingsItem as NavigationViewItem;
return;
}
Selected = _navigationView.MenuItems
.OfType<NavigationViewItem>()
.FirstOrDefault(menuItem => IsMenuItemForPageType(menuItem, e.SourcePageType));
}
private void Frame_NavigationFailed(object sender, NavigationFailedEventArgs e)
{
throw e.Exception;
}
private bool IsMenuItemForPageType(NavigationViewItem item, Type sourcePageType)
{
var pageKey = GetPageKey(item);
var navigatedPageKey = NavigationService.GetNameOfRegisteredPage(sourcePageType);
return pageKey == navigatedPageKey;
}
private Type GetPageKey(NavigationViewItem item) => Type.GetType(item.Tag.ToString());
Update 1
Am I wrong about the equality between ServiceLocator and ViewModelLocator?
Called ServiceLocator (or ViewModelLocator)
Essentially, the current task is to connected View and ViewModel. NavigationService is beyond the scope of this task. So shouldn't it be in ViewModelLocator?
As #Maess notes, the biggest challenge you face (right now) is refactoring the static dependencies into constructor injection. For example, your ShellViewModel should have a constructor like:
public ShellViewModel(INavigationService navigation)
Once you have done that, you can then set up a DI framework (like NInject) with all your dependencies (kind of like your SimpleIoC thing), and, ideally, pull one root object from the container (which constructs everything else). Usually that's the main view model of the application.
I've done this successfully on multiple projects, both WPF and UWP, and it works great. Only thing you have to be careful of is when creating view models at runtime (as you often do), do it by injecting a factory.
Related
My application is going on a break mode after hitting a user button that loads the app setup. I have registered the component in the bootstrapper class.
How can I register the constructor of the user controller in bootstrap class so as to avoid the break?
public class Bootstrapper
{
public IContainer Bootstrap()
{
var builder = new ContainerBuilder();
builder.RegisterType<LoginView>().AsSelf();
builder.RegisterType<SchoolSectionDataService>().As<ISchoolSectionDataService>();
builder.RegisterType<AdminView>().AsSelf();
builder.RegisterType<School>().AsSelf();
builder.RegisterType<MainSchoolSetupViewModel>().AsSelf();
return builder.Build();
}
}
and the user control is:
private MainSchoolSetupViewModel _viewModel;
public School(MainSchoolSetupViewModel schoolSetupViewModel)
{
InitializeComponent();
_viewModel = schoolSetupViewModel;
DataContext = _viewModel;
Loaded += UserControl_Loaded;
}
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
_viewModel.Load();
}
Unfortunately passing viewmodel into user control's constructor is not possible but there few ways around it. The main thing usually is when building combining DI and XAML and MVVM is that only the view models are registered into the container.
Couple options are mentioned in the comments:
Add a static IContainer property in your Bootstrap. Call it in you user control's constructor to get the VM:
public School()
{
InitializeComponent();
_viewModel = Bootstrap.Container.Resolve<MainSchoolSetupViewModel>();
...
Skip DI and instead create the viewmodel instance in XAML:
<UserControl.DataContext>
<local:SchoolViewModel/>
</UserControl.DataContext>
But it's quite likely that you want to there's other possibilities:
Use ViewModelLocator to help out with DI. This is well documented in this answer: https://stackoverflow.com/a/25524753/66988
The main idea is that you create a new ViewModelLocator class:
class ViewModelLocator
{
public SchoolViewModel SchoolViewModel
{
get { return Bootstrap.Container.Resolve<SchoolViewModel>(); }
}
}
And create a static instance of it in App.xaml and use it to create the data context of your user control:
DataContext="{Binding SchoolViewModel, Source={StaticResource ViewModelLocator}}">
For other solutions, one option is to check out source code of some of MVVM Frameworks, like Caliburn.Micro. From Caliburn.Micro you can find ViewModelLocator and ViewLocator which might interest you.
I'm trying to learn more about MVVM implementation in WPF and currently need some guidance on navigation using ViewModels. I'm following WPF navigation example from Rachel's blog and need a way to call Command of ApplicationViewModel from other ViewModel.
As per the blog, switching views from MainWindow is pretty clear, but I want to know more about inter-view navigation i.e. say I've Home, Product and Contact button on MainWindow along with View and ViewModel classes, now I want to open Contact page from some button inside Home view instead of MainWindow. I have written some code in Home ViewModel to achieve the same but I doubt whether this is the best practice of MVVM. And is there any way to achieve the same from HomeView.XAML?
Code Snippet from blog - ApplicationViewModel.cs
private ICommand _changePageCommand;
private IPageViewModel _currentPageViewModel;
private List<IPageViewModel> _pageViewModels;
public ApplicationViewModel()
{
// Add available pages in c'tor
PageViewModels.Add(new HomeViewModel(this));
PageViewModels.Add(new ProductsViewModel());
PageViewModels.Add(new ContactViewModel());
}
public ICommand ChangePageCommand
{
get
{
if (_changePageCommand == null)
_changePageCommand = new RelayCommand(
p => ChangeViewModel((IPageViewModel)p), p => p is IPageViewModel);
return _changePageCommand;
}
}
private void ChangeViewModel(IPageViewModel viewModel)
{
if (!PageViewModels.Contains(viewModel))
PageViewModels.Add(viewModel);
CurrentPageViewModel = PageViewModels.FirstOrDefault(vm => vm == viewModel);
}
Code Snippet from blog - ApplicationView.xaml
<Window.Resources>
<DataTemplate DataType="{x:Type local:HomeViewModel}">
<local:HomeView />
</DataTemplate>
<!-- Data template for other views -->
</Window.Resources>
<DockPanel>
<Border DockPanel.Dock="Left" BorderBrush="Black" BorderThickness="0,0,1,0">
<ItemsControl ItemsSource="{Binding PageViewModels}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button Content="{Binding Name}"
Command="{Binding DataContext.ChangePageCommand,
RelativeSource={RelativeSource AncestorType={x:Type Window}}}"
CommandParameter="{Binding }"/>
<!--All closing tags-->
My code inside HomeViewModel.cs
// This is the command to get bind with my button inside Home view to invoke Contact view
private ICommand _loadContactCommand;
public ICommand LoadContactCommand
{
get
{
if (_loadContactCommand == null)
_loadContactCommand = new RelayCommand(p => LoadOtherView());
return _loadContactCommand;
}
}
private void LoadOtherView()
{
// _appVM is the instance of 'ApplicationViewModel' which is being set from c'tor
// Even I'm thinking to pass Contact view member of ApplicationViewModel class here,
// as I need exactly the same instance of the Contact which has been created earlier
_appVM.ChangePageCommand.Execute(new ContactViewModel());
}
There's a couple of ways I'd do this.
The first, if the action is a service type of interaction, which I think this is a reasonably good example of, I would describe the action in an interface and inject it as a dependency into the ViewModels that need it.
This is effectively what you are doing, but it's worth abstracting it out into an interface. This provides less tight coupling between the two ViewModels.
Here is an example of wrapping up the functionality in an IPageDisplay interface:
public interface IPageDisplay
{
IPageViewModel GetCurrentPage();
void ChangeViewModel(IPageViewModel newPage);
}
Your ApplicationViewModel implements it and has the exact same methods it did before:
public class ApplicationViewModel: IPageDisplay
{
// implement like you are doing
You're HomeViewModel then takes as an interface, not the 'whole' ViewModel:
class HomeViewModel
{
HomeViewModel(IPageDisplay pageDisplay) {//constructor stuff}
private void LoadOtherView()
{
// Instead of interacting with a whole ViewModel, we just use the interface
_pageDisplay.ChangePageCommand.Execute(new ContactViewModel());
}
This is 'safer' as it's more abstract. You can test HomeViewModel without creating a AppViewModel by just mocking the IPageDisplay. You can change how pages are displayed or the implementation of AppViewModel, you can also display your pages in any other kind of location, by having some other implementation of IPageDisplay.
It's worth noting that any page that needs to perform navigation actions will require an IPageDisplay. It can be troublesome matching up all these dependencies if you have many of them - that's where something like a Dependency Injection framework can really help out.
The second would be a mediator pattern as suggested in the comments. You could have a common mediator PageManager that defines the ChangeViewModel(IPageViewModel newPage); method and fires a ChangeViewModelRequest event or callback. The ApplicationViewModel, and any other ViewModels that want to change the current page accept the PageManager instance as a dependency. ApplicationViewModel listens to the event, the other's call ChangeViewModelRequest to trigger it.
Again, a Dependency Injection will need to be managed effectively if this is in a complex application.
This naturally leads onto the third. Which is a extension of the mediator pattern, an Event Aggregator.
An event aggregator is a generic service that allows all different ViewModels to raise, or subscribe to application wide events. It's definitely worth looking at.
Here, your ApplicationViewModel subscribes to the event:
public class ApplicationViewModel
{
private EventAgregator _eventAggregator;
ApplicationViewModel(EventAgregator eventAggregator)
{
this._eventAggregator = eventAggregator;
_eventAggregator.Subscribe('ChangeViewModelRequest', (EventArgs eventArgs) => ChangeViewModel(eventArgs.Parameter))
}
private void ChangeViewModel(IPageViewModel viewModel)
{
if (!PageViewModels.Contains(viewModel))
PageViewModels.Add(viewModel);
CurrentPageViewModel = PageViewModels.FirstOrDefault(vm => vm == viewModel);
}
}
And the HomeViewModel publishes to the event:
private void LoadOtherView()
{
_eventAggregator.Publish("ChangeViewModelRequest", new EventArgs(new ContactViewModel()));
}
There are plenty of Event Aggregators you can use, some built into MVVM frameworks like Prism.
While, like all the others, this is a dependency - it's a very generic one. Chances are, most of your ViewModels will need access to the aggregator instance and have it as a dependency, as it could be used for almost all inter-view-model communication. Simply having all VMs pass it to any created VMs in the constructor could work for a simple application. But I'd still say something that supports dependency injection (say, factory pattern?) would be worth implementing.
Edit:
Here's what you need for your HomeViewModel:
public class HomeViewModel : IPageViewModel // doesn't implement IPageDisplay
{
private IPageDisplay _pageDisplay;
public HomeViewModel(IPageDisplay pageDisplay)
{
// HomeViewModel doesn't implement IPageDisplay, it *consumes* one
// as a dependency (instead of the previous ApplicationViewModel).
// Note, that the instance you're passing still is the ApplicationViewModel,
// so not much has actually changed - but it means you can have another
// implementation of IPageDisplay. You're only linking the classes together
// by the functionality of displaying a page.
_pageDisplay= pageDisplay;
}
public string Name
{
get
{
return "Home Page";
}
}
private ICommand _loadDashboardCommand;
public ICommand LoadDashboardCommand
{
get
{
if (_loadDashboardCommand == null)
{
_loadDashboardCommand = new RelayCommand(
p => LoadOtherView());
}
return _loadDashboardCommand;
}
}
private void LoadOtherView()
{
// Here you have the context of ApplicatiomViewModel like you required
// but it can be replaced by any other implementation of IPageDisplay
// as you're only linking the little bit of interface, not the whole class
_pageDisplay.ChangeViewModel(new DashboardViewModel());
}
}
}
I am developing a C#/WPF/MVVM/UWP app which uses a ViewModelLocator which looks like this:
public class ViewModelLocator
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance",
"CA1822:MarkMembersAsStatic",
Justification = "This non-static member is needed for data binding purposes.")]
public MainPageViewModel MainPage
{
get
{
return ServiceLocator.Current.GetInstance<MainPageViewModel>();
}
}
static ViewModelLocator()
{
// DEBUG LINE: var test = Views.ViewLocator.MainPageKey;
ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
if (ViewModelBase.IsInDesignModeStatic)
{
SimpleIoc.Default.Register<IDataService, Design.DesignDataService>();
}
else
{
SimpleIoc.Default.Register<IDataService, DataService>();
}
SimpleIoc.Default.Register<MainPageViewModel>();
}
}
I have another class, a ViewLocator, for navigation purposes which looks like this:
public class ViewLocator
{
public static readonly string MainPageKey = typeof(MainPage).Name;
public static readonly string WorkPageKey = typeof(WorkPage).Name;
static ViewLocator()
{
ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
var navigationService = new NavigationService();
navigationService.Configure(MainPageKey, typeof(MainPage));
navigationService.Configure(WorkPageKey, typeof(WorkPage));
SimpleIoc.Default.Register<INavigationService>(() => navigationService);
SimpleIoc.Default.Register<IDialogService, DialogService>();
}
}
Before, both classes were combined in ViewModelLocator, however i figured that the ViewModelLocator as part of the "ViewModels-Side-of-things" should be unaware of the views and it's types, which is why I refactored that code into two classes.
My MainPageView then has a button, which triggers a navigation command in the MainPageView.cs
public class MainPageViewModel : ViewModelBase
{
private INavigationService _navigationService;
public RelayCommand CreateNewImageCommand { get; private set; }
public MainPageViewModel(INavigationService navigationService)
{
_navigationService = navigationService;
CreateNewImageCommand = new RelayCommand(CreateNewImage, () => true);
}
public void CreateNewImage()
{
_navigationService.NavigateTo(Views.ViewLocator.WorkPageKey);
}
}
For completeness, here is my App.xaml
<Application
...>
<Application.Resources>
<v:ViewLocator x:Key="ViewLocator" />
<vm:ViewModelLocator x:Key="ViewModelLocator" />
</Application.Resources>
Now what happens is this: if I don't have the DEBUG LINE in ViewModelLocator, at the point at which MainPage requests its ViewModel from the ViewModelLocator, the constructor of ViewLocator has not been called yet and return ServiceLocator.Current.GetInstance<MainPageViewModel>(); throws an exception. If I include the DEBUG LINE, this forces the ViewLocator Constructor to be run first, and everything works fine.
How can I achieve this behaviour without that odd debug line?
You are running into the reason most developers do not use static classes and a service locator.
As suggested in your comments try using dependency injection. This allows inversion of control for the component that manages this wiring.
Look into MEF or Unity as a framework to use rather than rolling your own IoC. Both have advantages and disadvantages but either will work. They also allow for easier and cleaner testing.
MEF
Unity
Despite of all the comments and other answers, I think that I was on the track after all. To solve or rather bypass this problem, I have created added bootstrapping of the SimpleIoC Container in the Startup of the App and move the code from the ViewLocator's constructor there.
I also removed the ServiceLocator calls, which was sort of redundant and rely on SimpleIoC.Default now directly.
The Navigator is still injected into the ViewModels by the SimpleIoC Container. The ViewModelLocator however is necessary work in conjuction with the XAML code.
I recommend this answer as a starting point for others who are also struggling with this issue.
https://stackoverflow.com/a/25524753/2175012
After all, I have taken the side that ServiceLocators are no anti pattern but have to be used carefully.
Here Caliburn.Micro was successfully combined with ModernUI.
But if we want to use multiple windows we also need to re-implement Caliburn's WindowManager to work properly with ModernUI. How can it be done?
UPDATE:
(Additional question about IoC-Container/Dependency Injection)
Ok, as I get it: I used a Constructor Injection here:
public class BuildingsViewModel : Conductor<IScreen>
{
public BuildingsViewModel(IWindowManager _windowManager)
{
windowManager = _windowManager;
}
}
As far as BuildingsViewModel resolved from IoC container,
container itself injected ModernWindowManager implementation of IWindowManager interface because of this line in Bootstrapper's Configure() method:
container.Singleton<IWindowManager, ModernWindowManager>();
If I resolving an object instance from container, it injects all needed dependencies. Like a tree.
1) So now I wonder how can I replace this line using an injection(with interface)?
_windowManager.ShowWindow(new PopupViewModel());
2) If I want my whole project match DI pattern, all objects instances must be injected into ModernWindowViewModel, that resolves from container first?
3) Is it okay to use Caliburn's SimpleContainer for whole project, or better use mature framework like Castle Windsor? Should I avoid mixing?
UPDATE2:
4) Integrating an IoC container into an existing application requires creating this container first(in Main() method of console app for example), and then all object instanses must grow from it with injected dependencies?
Simply create your own derived WindowManager and override EnsureWindow:
public class ModernWindowManager : WindowManager
{
protected override Window EnsureWindow(object rootModel, object view, bool isDialog)
{
var window = view as ModernWindow;
if (window == null)
{
window = new ModernWindow();
window.SetValue(View.IsGeneratedProperty, true);
}
return window;
}
}
Any views that you want to use as popups must be based on ModernWindow and must either use a LinkGroupCollection or you must set the ContentSource property of the window, otherwise there will be no content.
You could possibly make this View-First but it works ViewModel-First using the method above.
e.g. to popup my PopupView I did the following
PopupView.xaml
<mui:ModernWindow x:Class="TestModernUI.ViewModels.PopupView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mui="http://firstfloorsoftware.com/ModernUI"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300" ContentSource="/ViewModels/ChildView.xaml">
</mui:ModernWindow>
PopupViewModel.cs
public class PopupViewModel : Screen
{
// Blah
}
Code to popup the view from another ViewModel:
public void SomeMethod()
{
_windowManager.ShowWindow(new PopupViewModel()); // Or use injection etc
}
Don't forget to register ModernWindowManager in place of WindowManager in your container!
e.g. using CM's SimpleContainer
container.Singleton<IWindowManager, ModernWindowManager>();
Obviously the only downside I can see to the above is that you can't seem to put content directly in a ModernWindow, so you have to have two UserControls for every popup!
A workaround would be to change EnsureWindow in ModernWindowManager so that it created a UserControl based on ModernWindow and set the ContentSource to the URI of the view you want to load, this will trigger the content loader and wire up your ViewModel. I'll update if I get a minute to try it.
Update:
Ok, so at the moment it's very hacky, but this could be a starting point for something useful. Basically I'm generating a URI based on the namespace and name of the view.
I'm sure there is a more reliable way of doing this, but for my test project it works:
protected override Window EnsureWindow(object rootModel, object view, bool isDialog)
{
var window = view as ModernWindow;
if (window == null)
{
window = new ModernWindow();
// Get the namespace of the view control
var t = view.GetType();
var ns = t.Namespace;
// Subtract the project namespace from the start of the full namespace
ns = ns.Remove(0, 12);
// Replace the dots with slashes and add the view name and .xaml
ns = ns.Replace(".", "/") + "/" + t.Name + ".xaml";
// Set the content source to the Uri you've made
window.ContentSource = new Uri(ns, UriKind.Relative);
window.SetValue(View.IsGeneratedProperty, true);
}
return window;
}
My full namespace for my view was TestModernUI.ViewModels.PopupView and the URI generated was /ViewModels/PopupView.xaml which then was loaded and bound via the content loader automagically.
Update 2
FYI here is my Bootstrapper configure method:
protected override void Configure()
{
container = new SimpleContainer();
container.Singleton<IWindowManager, ModernWindowManager>();
container.Singleton<IEventAggregator, EventAggregator>();
container.PerRequest<ChildViewModel>();
container.PerRequest<ModernWindowViewModel>();
container.PerRequest<IShell, ModernWindowViewModel>();
}
Here I create the container, and register some types.
The CM services such as WindowManager and EventAggregator are both registered against their respective interfaces and as singletons so only 1 instance of each will be available at run time.
The view models are registered as PerRequest which creates a new instance every time you request one from the container - this way you can have the same window popup multiple times without strange behaviour!
These dependencies are injected into the constructor of any objects resolved at run time.
Update 3
In answer to your IoC questions:
1) So now I wonder how can I replace this line using an injection(with interface)? _windowManager.ShowWindow(new PopupViewModel());
Since your viewmodels will now usually need dependencies you need to have some way of injecting them into the instances. If PopupViewModel had several dependencies, you could inject them into the parent class but this would couple the parent viewmodel to PopupViewModel in some way.
There are a couple of other methods you can use to get an instance of PopupViewModel.
Inject it!
If you register PopupViewModel as PerRequest you will get a new instance of it every time you request it. If you only need one popup instance in your viewmodel you can just inject it:
public class MyViewModel
{
private PopupViewModel _popup;
private IWindowManager _windowManager;
public MyViewModel(PopupViewModel popup, IWindowManager windowManager)
{
_popup = popup;
_windowManager = windowManager;
}
public void ShowPopup()
{
_windowManager.ShowPopup(_popup);
}
}
The only downside is that the instance will be the same one if you need to use it multiple times in the same viewmodel, though you could inject multiple instances of PopupViewModel if you knew how many you needed at the same time
Use some form of on-demand injection
For dependencies which are required later on you can use on-demand injection such as a factory
I don't think Caliburn or SimpleContainer support factories out of the box, so the alternative is to use IoC.Get<T>. IoC is a static class which lets you access your DI container after instantiation
public void ShowPopup()
{
var popup = IoC.Get<PopupViewModel>();
_windowManager.ShowWindow(popup);
}
You need to make sure you have correctly registered the container in your bootstrapper and delegated any calls to CM's IoC methods to the container - IoC.Get<T> calls the bootstrapper's GetInstance and other methods:
Here's an example:
public class AppBootstrapper : BootstrapperBase {
SimpleContainer container;
public AppBootstrapper() {
Initialize();
}
protected override void Configure() {
container = new SimpleContainer();
container.Singleton<IWindowManager, ModernWindowManager>();
container.Singleton<IEventAggregator, EventAggregator>();
container.PerRequest<IShell, ModernWindowViewModel>();
// Register viewmodels etc here....
}
// IoC.Get<T> or IoC.GetInstance(Type type, string key) ....
protected override object GetInstance(Type service, string key) {
var instance = container.GetInstance(service, key);
if (instance != null)
return instance;
throw new InvalidOperationException("Could not locate any instances.");
}
// IoC.GetAll<T> or IoC.GetAllInstances(Type type) ....
protected override IEnumerable<object> GetAllInstances(Type service) {
return container.GetAllInstances(service);
}
// IoC.BuildUp(object obj) ....
protected override void BuildUp(object instance) {
container.BuildUp(instance);
}
protected override void OnStartup(object sender, System.Windows.StartupEventArgs e) {
DisplayRootViewFor<IShell>();
}
Castle.Windsor supports factories so that you can Resolve and Release your components and manage their lifetime more explicitly, but I won't go into that here
2) If I want my whole project match DI pattern, all objects instances must be injected into ModernWindowViewModel, that resolves from container first?
You only need to inject the dependencies that the ModernWindowViewModel needs. Anything that is required by children is automatically resolved and injected e.g.:
public class ParentViewModel
{
private ChildViewModel _child;
public ParentViewModel(ChildViewModel child)
{
_child = child;
}
}
public class ChildViewModel
{
private IWindowManager _windowManager;
private IEventAggregator _eventAggregator;
public ChildViewModel(IWindowManager windowManager, IEventAggregator eventAggregator)
{
_windowManager = windowManager;
_eventAggregator = eventAggregator;
}
}
In the above situation, if you resolve ParentViewModel from the container - the ChildViewModel will get all it's dependencies. You don't need to inject them into the parent.
3) Is it okay to use Caliburn's SimpleContainer for whole project, or better use mature framework like Castle Windsor? Should I avoid mixing?
You can mix, but it might be confusing as they won't work with each other (one container won't know about the other). Just stick with one container, and SimpleContainer is fine - Castle Windsor has a lot more features, but you might never need them (I've only used a few of the advanced features)
4) Integrating an IoC container into an existing application requires creating this container first(in Main() method of console app for example), and then all object instanses must grow from it with injected dependencies?
Yes, you create the container, then you resolve the root component (in 99.9% of applications there is one main component which is called the composition root), and this then builds the full tree.
Here is an example of a bootstrapper for a service based application. I'm using Castle Windsor and I wanted to be able to host the engine in a Windows service or in a WPF application or even in a Console Window (for testing/debug):
// The bootstrapper sets up the container/engine etc
public class Bootstrapper
{
// Castle Windsor Container
private readonly IWindsorContainer _container;
// Service for writing to logs
private readonly ILogService _logService;
// Bootstrap the service
public Bootstrapper()
{
_container = new WindsorContainer();
// Some Castle Windsor features:
// Add a subresolver for collections, we want all queues to be resolved generically
_container.Kernel.Resolver.AddSubResolver(new CollectionResolver(_container.Kernel));
// Add the typed factory facility and wcf facility
_container.AddFacility<TypedFactoryFacility>();
_container.AddFacility<WcfFacility>();
// Winsor uses Installers for registering components
// Install the core dependencies
_container.Install(FromAssembly.This());
// Windsor supports plugins by looking in directories for assemblies which is a nice feature - I use that here:
// Install any plugins from the plugins directory
_container.Install(FromAssembly.InDirectory(new AssemblyFilter("plugins", "*.dll")));
_logService = _container.Resolve<ILogService>();
}
/// <summary>
/// Gets the engine instance after initialisation or returns null if initialisation failed
/// </summary>
/// <returns>The active engine instance</returns>
public IIntegrationEngine GetEngine()
{
try
{
return _container.Resolve<IIntegrationEngine>();
}
catch (Exception ex)
{
_logService.Fatal(new Exception("The engine failed to initialise", ex));
}
return null;
}
// Get an instance of the container (for debugging)
public IWindsorContainer GetContainer()
{
return _container;
}
}
Once the bootstrapper is created, it sets up the container and registers all services and also plugin dlls. The call to GetEngine starts the application by resolving Engine from the container which creates the full dependency tree.
I did this so that it allows me to create a service or a console version of the application like this:
Service Code:
public partial class IntegrationService : ServiceBase
{
private readonly Bootstrapper _bootstrapper;
private IIntegrationEngine _engine;
public IntegrationService()
{
InitializeComponent();
_bootstrapper = new Bootstrapper();
}
protected override void OnStart(string[] args)
{
// Resolve the engine which resolves all dependencies
_engine = _bootstrapper.GetEngine();
if (_engine == null)
Stop();
else
_engine.Start();
}
protected override void OnStop()
{
if (_engine != null)
_engine.Stop();
}
}
Console App:
public class ConsoleAppExample
{
private readonly Bootstrapper _bootstrapper;
private IIntegrationEngine _engine;
public ConsoleAppExample()
{
_bootstrapper = new Bootstrapper();
// Resolve the engine which resolves all dependencies
_engine = _bootstrapper.GetEngine();
_engine.Start();
}
}
Here's part of the implementation of IIntegrationEngine
public class IntegrationEngine : IIntegrationEngine
{
private readonly IScheduler _scheduler;
private readonly ICommsService _commsService;
private readonly IEngineStateService _engineState;
private readonly IEnumerable<IEngineComponent> _components;
private readonly ConfigurationManager _configurationManager;
private readonly ILogService _logService;
public IntegrationEngine(ICommsService commsService, IEngineStateService engineState, IEnumerable<IEngineComponent> components,
ConfigurationManager configurationManager, ILogService logService)
{
_commsService = commsService;
_engineState = engineState;
_components = components;
_configurationManager = configurationManager;
_logService = logService;
// The comms service needs to be running all the time, so start that up
commsService.Start();
}
All of the other components have dependencies, but I don't inject those into the IntegrationEngine - they are handled by the container
I recently started a WPF project which follows the MVVM pattern, of course. I'm trying to resolve the object graph for the view models once and once only (in the composition root, that is in the Startup event handler of the application) in order not to have any other class to be dependent on my IoC container:
public partial class App : Application
{
private void OnStartup(object sender, StartupEventArgs e)
{
// Composition Root
var container = new UnityContainer();
container.RegisterType<IResidentListViewModel, ResidentListViewModel>();
container.RegisterType<IMainViewModel, MainViewModel>();
container.RegisterType<IDataService, DataService>();
var mainWindow = new MainWindow(container.Resolve<IMainViewModel>());
Current.MainWindow = mainWindow;
mainWindow.Show();
}
}
ResidentListViewModel in turn depends on IDataService:
private readonly IDataService dataService;
public ResidentListViewModel(IDataService dataService)
{
if (dataService == null)
throw new ArgumentNullException("dataService");
this.dataService = dataService;
}
Which is not an issue, as the container will resolve that dependency alright.
However, ResidentListviewModel has a Residents property that hits IDataService:
private readonly ObservableCollection<IResidentViewModel> residents = new ObservableCollection<IResidentViewModel>();
public ObservableCollection<IResidentViewModel> Residents
{
get
{
if (this.residents == null)
LoadResidents();
return this.residents;
}
}
The trouble starts, when data is being loaded:
private async Task LoadResidents()
{
if (!IsLoading)
{
IsLoading = true;
var models = await this.dataService
.ListResidents();
var viewModels = models
.OrderBy(m => m.Name)
.ThenBy(m => m.Vorname)
.Select(m => new ResidentViewModel(m.Z_PF, string.Format("{0}, {1}", m.Name, m.Vorname)));
residents.Clear();
foreach (var viewModel in viewModels)
residents.Add(viewModel);
IsLoading = false;
}
}
I know, I know, repeatedly adding to an ObservableCollection is a no-go, but please bear with me here. See that shiny 'new' keyword there? That's the true culprit. I have no idea how to get rid of it without resigning to a service locator ('instance factory'), which in turn is an anti-pattern according to my favorite DI book author, Mark Seemann (yes, I do have the book and would recommend it to any C# developer).
I could, of course, inject the list of VMs itself, but that would move retrieval of data to the composition root (sounds like a bad idea) and I can just as easily come up with a scenario where the user selects an entry and the code has to retrieve data depending on that selection, putting me back on square one.
So the question is: Is there a way to handle this issue with that same single call from composition root?
You were close. Not instance factory anti-pattern, but abstract factory pattern:
var viewModels = models
.OrderBy(m => m.Name)
.ThenBy(m => m.Vorname)
.Select(m => residentViewModelFactory.CreateInstance(m));
The residentViewModelFactory is of course dependency provided as interface via constructor injection, which makes everything fine and testable, and of course setup-able from composition root (you register factory as one of components).