Deserialization and unity

Feb 3, 2010 at 8:59 AM


I'm using System.Xml.Serialization.XmlSerializer to deserialize an xml into an object. In this case Deserialize of XmlSerializer instantiates the object. Now I want to inject a unity container instance that I want to be available during deserialization (in the IXmlSerializable.ReadXml(XmlReader reader) method). How can I do this without using a static variable that will hold the container?


Feb 6, 2010 at 3:34 AM

As far as I know, the problem is that the XmlSerializer doesn't have any hook to allow extra context into the deserialization process.

There are some gyrations you could do to sorta-kinda make it work, but I'd need more details on exactly why you want the container available before making any suggestions.



Feb 6, 2010 at 8:56 AM

What I want is simple but I'm almost sure it's not possible.

I want to deserialize using XmlSerializer but I want my objects to be instantiated by a container, since my classes have stuff in their constructors that need to be injected.

Feb 7, 2010 at 2:57 AM

As far as I know, there's no way to do what you want, XmlSerializer just doesn't have the hooks to allow it.

If you move the dependencies to properties, you could deserialize and then call container.BuildUp on the object to get them filled in after deserialization.