Inversion of Control (IOC) with XAML
I met Simon Ferquel this week at the 2010 MVP Summit. I gave a talk about XAML on Wednesday, and later that day blogged one of my samples from the talk: “XamlSchemaContext/XamlType/XamlMember – a command line example”.
He commented on that post with:
Hi Rob,
As I understand, creating a custom XamlSchemaContext could be a way to make Xaml content integrate with an IoC, isn't it?
I can imagine a scenario where you can then write something like :
<Foo>
<Foo.Bar><IBar /></Foo.Bar>
</Foo>
With IBar being an interface that is resolved by the IoC. Same thing could apply with types without default constructor whose dependencies could be injected by the IoC-enabled schema context.
If you confirm that it is doable, I'll make a sample of a Unity-enabled Xaml Schema Context.
by Simon Ferquel
Turns out that subclassing XamlSchemaContext and XamlType seems to have worked quite nicely. See Simon’s “[Xaml] IoC-enabled Xaml parser” The basic idea is the custom schema context returns a XamlType for IBar that says it knows how to be created. When the XamlObjectWriter calls it to create the IBar, it can find an appropriate IBar to return.
Other Approaches
Other people have accomplished Invesrion of Control other ways…
- John “Z-Bo” Zabroski uses a custom markup extension. (via comment)
- I’ll add more links as I find other approaches or comments mention them.