WP7 SimpleContainer and multiple constructors

May 7, 2011 at 11:04 AM

Hi, I'm new to CM and experimenting with WP7. By now I'm using the SimpleContainer to inject dependencies into my VM's. I register some singleton models like:

container.RegisterSingleton(typeof(UnitConverter), null, typeof(UnitConverter));

This works fine when the model has just a single default constructor. The UnitConverter model here instead has 2 constructors, a default one and one accepting an XML document with some parameters. If using the default constructor some default parameters will be loaded. So its implementations are like:

public UnitConverter()
// ... load default ...

public UnitConverter(XDocument doc)
if (doc == null) throw new ArgumentNullException();
// .. load from doc ..

Looking at the SimpleContainer I can see it chooses the ctor with the max number of parameters, so it's going to choose the 2nd; anyway it cannot of course resolve XDocument and thus passes into it a null, which throws the exception. I tried changing the 2nd ctor code so that when it gets a null doc it falls back to the default parameters rather than throwing. Anyway (apart from the fact that I will not always have access to the model code), to my surprise the SimpleContainer keeps raising a null object ref exception at Activator.CreateInstance (called with 1 null parameter, as expected) and if I place a breakpoint in both constructors of my model they are never reached. What's going here? I'm planning to use MEF or Ninject for IoC, but for the moment I'd just like to get acquanted with CM and WP7 and I'd like to learn...


May 7, 2011 at 1:49 PM

I'm not sure what's going on exactly. But, it's probably just not able to create an instance of XDocument. You can get around your issues by creating a static Factory method with the XDocument parameter. It's a "simple" container so it's not really guaranteed to be smart or handle the edge cases correctly.