2

I'm using a custom class to perform validation in a WPF app and have defined a class which inherits from ValidationRule. The class has a dependancy which I would like AutoFac to inject at runtime, but the Visual Studio 2010 XAML designer needs a parameterless constructor in order to work.

It seems the only solution is to create a DependencyProperty for the dependency and bind it in XAML, but that means the dependency is publicly accessible and mutable, neither of which I want.

Is there any way to pass a dependency in to a class you intend to use in XAML which will do all of the following?

  • Not break the designer.
  • Keep the dependency private.
  • Make sure the dependency is set before the class is used.
andrej351
  • 904
  • 3
  • 18
  • 38

2 Answers2

2

How badly do you want to do it?

The features in XAML 2009 provide the following elements which could help you:

  • x:Arguments would allow you to pass an argument to the constructor. Can this argument be somehow bound to a property of your view model?

  • x:FactoryMethod allows you to specify the method which creates the object. I assume this can be a method of your window or usercontrol, which would have access to your dependency container.

But here's the problem: XAML 2009 can only be loaded at runtime via a XAML Reader, and can not be compiled. (See Can't get the new 2009 XAML primitives working, why?).

So global static objects (eurgh) might still be the less painful solution.


Later Edit: I reread your question, and realised you had put "Not break the designer" as one of you requirements. This excludes XAML 2009 from the possible solutions.
Community
  • 1
  • 1
Andrew Shepherd
  • 44,254
  • 30
  • 139
  • 205
-2

This is an excellent question. I used techniques demosontrated here to keep the designer working: http://jonas.follesoe.no/2008/07/24/youcard-re-visited-implementing-dependency-injection-in-silverlight/

It not only keeps it working but you can use the technique to put mocks into the designer. Very handy.

Dessus
  • 2,147
  • 1
  • 14
  • 24
  • -1 from me, because it doesn't answer the specific question. (There might be an answer somewhere in the 2000 word blog you linked to, in which case you should extract the answer and place it here) – Andrew Shepherd Dec 19 '11 at 05:01
  • That is a very interesting blog post and we are using similar techniques to enable ViewModel binding in XAML and to get AutoFac to take care of dependencies. The problem is that at the end he actually isn't declaring any custom classes in XAML, he's using a binding expression and for my specific example we're talking about using XAML collection syntax to add items to a property with no setter. See here: http://msdn.microsoft.com/en-us/library/system.windows.data.binding.validationrules.aspx Thanks though. – andrej351 Dec 19 '11 at 08:04