Thursday, December 8, 2016

WPF and Castle Windsor

Before using Castle Windsor I used to implement a provider keeping static references to view-models and reference these in the View using Xaml Databinding... something like DataContext="{x:static ViewModelProvider.MainViewModel}".

Now after getting to know Castle Windsor and its ability to handle references it makes totally sense to solve that differently (or to be concrete: to solve that better). For development time we still need to hard code a design-time-view-model cause else we loose all the features of the IDE... Nevertheless Windsor should take over the control about the wiring of View and ViewModel. Main reason therefore is the power (features like Interceptors) and the flexibility (DynamicParameters, Load Config from XML, work with interfaces) coming up with.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
    public class ActivatorWPFVM<T> : DefaultComponentActivator
    {
        public ActivatorWPFVM(ComponentModel model, IKernelInternal kernel, ComponentInstanceDelegate onCreation, ComponentInstanceDelegate onDestruction)
            : base(model, kernel, onCreation, onDestruction)
        {

        }
        protected override object CreateInstance(CreationContext context, ConstructorCandidate constructor, object[] arguments)
        {
            var component = base.CreateInstance(context, constructor, arguments);
            if(component is Window)
            {
                ((Window)component).DataContext = DIProvider.Container.Resolve<T>();
            }
            return component;
        }
    }

So by calling...

container.Register(
   Component
      .For<MainWindow>() 
      .Activator<ActivatorWPFVM<MainViewModel> >() 
      .LifestyleTransient());

... we can create a Window reference with an already wired up connection to its ViewModel (in config section where it should be).

kr,
Daniel

No comments: