Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>To stay as close to your example code as possible, you can introduce yet another level of indirection in the form of an IViewPopulator:</p> <pre><code>public interface IViewPopulator { void Populate(IView view); } </code></pre> <p>You can now implement your SomeViewFactory like this:</p> <pre><code>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; } } </code></pre> <p>This separates the creation of Views and the population of ViewModels, adhering to the <a href="http://en.wikipedia.org/wiki/Single_responsibility_principle" rel="noreferrer">Single Responsibility Principle</a>. To a certain extent, it is also an example of <a href="http://blog.ploeh.dk/2010/02/02/RefactoringToAggregateServices.aspx" rel="noreferrer">Service Aggregation</a>.</p> <p>You can now implement IViewPopulator as a concrete type that takes normal dependencies:</p> <pre><code>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; } } </code></pre> <p>There are likely to be other ways you could model the relationship between IView and IViewModel, but the above represents one possible solution.</p> <p>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.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload