I haven't been able to find guidance on registering views and viewModels with AutoFac. My goal is to have it so when a view is created (by the system or through a view creation service), the viewModel specified is resolved by AutoFac and applied to the view's DataContext.
Here's the somewhat hacky solution I have so far:
builder.Register(t => new CatView() { DataContext = t.Resolve<CatListViewModel>() });
This works in that the viewModel is instantiated and applied as the DataContext when the view is created. But the viewModel's Dispose() method won't be called until the scope's lifetime ends (when the application is closed?), which could lead to memory leaks since a new viewModel is created every time the view is opened.
I believe other DI frameworks such as Ninject and Prism do have view/viewModel specific registration calls, which makes me think I'm doing something wrong. Please let me know of a better approach to view/viewModel registration with AutoFac.
You're doing it all back-to-front. One of the main reasons for doing MVVM is to facilitate unit-testing i.e. your application should be able to run without creating any views at all!
With that in mind, the usual way of mapping the two in WPF is via DataTemplates, and your choice of DI framework shouldn't make any difference. Basically you do this:
<DataTemplate DataType="{x:Type vm:MyViewModelType">
<views:MyViewControl />
</DataTemplate>
Now anything that uses a ContentPresenter (ListBoxes etc) will populate itself with that view whenever its content bound to the corresponding view model. You can also do it explicitly like this:
<ContentControl Content="{Binding SomeViewModelProperty}" />
If you're adament about doing things the hard way then take a look at Jonathan Yates' "Adventures in Xamarin Forms" tutorials, the pages themselves are unfortunately long gone but you can still read it all on the Wayback Machine. It's all Xamarin of course, but very easy to port to WPF. I did use it on a few projects, but eventually replaced it all with a custom DataTypeSelector that just implemented the WPF-style DataTemplates.