1

On the following code:

var serializer = new XmlSerializer(typeof(MyPOCOType));
using (var reader = XmlReader.Create(fileName))
{
    var pocoInstance = (MyPOCOType)serializer.Deserialize(reader);
}

I am using ninject.

The MyPOCOType has an dependency that is passed by constructor injection.

The instance of MyPOCOType is being created by the Deserialize method, so the dependencies are not provided.

There are another way to do that without separate the state from my MyPOCOType and without use [Inject] attribute? (still using Constructor injection)

Vinicius Gonçalves
  • 2,514
  • 1
  • 29
  • 54
  • What about creating another constructor that accept Xml as one parameter, and then use IocContainer to create instance while passing Xml as Parameter? – Gaurav Sharma Mar 03 '15 at 17:12
  • 1
    Don't attempt to inject dependencies into data objects: https://stackoverflow.com/questions/28715966/entity-framework-object-materialization-and-dependency-injection – Steven Mar 03 '15 at 19:04

1 Answers1

4

XmlSerializer does not support this, and does not have hooks for external construction. So : no, basically.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • @ViniciusGonçalves not really, unless you know of an alternative but feature-complete xml serializer – Marc Gravell Mar 03 '15 at 17:19
  • A workaround I have used is to use property injection right after deserialization. If you wrap the deserialization step into an abstract factory, you can inject the container into the factory (similar to what you would do in IControllerFactory) and call the BuildUp method (or equivalent) to inject the properties before returning the instance. Not very pretty, but at least it is workable. – NightOwl888 Mar 05 '15 at 10:22