It\'s not quite clear to me how I can design so I keep the reference to the DI-container in the composition root for a Silverlight + MVVM application.
I have the followi
To stay as close to your example code as possible, you can introduce yet another level of indirection in the form of an IViewPopulator:
public interface IViewPopulator
{
void Populate(IView view);
}
You can now implement your SomeViewFactory like this:
public class SomeViewFactory : ISomeViewFactory
{
private readonly IViewPopulator populator;
public SomeViewFactory(IViewPopulator populator)
{
if (populator == null)
{
throw new ArgumentNullException("populator");
}
this.populator = populator;
}
public IView CreateView()
{
IView view = new SomeView();
this.populator.Populate(view);
return view;
}
}
This separates the creation of Views and the population of ViewModels, adhering to the Single Responsibility Principle. To a certain extent, it is also an example of Service Aggregation.
You can now implement IViewPopulator as a concrete type that takes normal dependencies:
public class SomeViewPopulator : IViewPopulator
{
private readonly IDependency dep;
public SomeViewPopulator(IDependency dep)
{
if (dep == null)
{
throw new ArgumentNullException("dep");
}
this.dep = dep;
}
public void Populate(IView view)
{
var vm = // Perhaps use this.dep to create an instance of IViewModel...
view.ViewModel = vm;
}
}
There are likely to be other ways you could model the relationship between IView and IViewModel, but the above represents one possible solution.
The key is to keep extracting abstractions until each have a well-defined responsibility. This exercise is really not about making code Container-agnostic at all, but eventually about adhering to SOLID principles.