I am working on a project that uses dependency injection through Ninject. So far, it has worked very well, and I really like DI, but now I decided that I need to serialize some objects, and it is difficult for me to do this with DI templates.
Let's say I have a class called Foo that has a list of bars and makes them through a factory, for example:
public class Foo { private List<Bar> _bars; private BarFactory _barFactory; ... public void MakeBar() { _bars.Add(_barFactory.MakeBar()); } }
Here is the Bar that is created when _barFactory.MakeBar() called. I want Bar to be serializable:
public class Bar : ISerializable { private List<IPickle> _pickles; private PickleFactory _pickleFactory; public Bar(PickleFactory factory) { _pickleFactory = factory; } public void MakePickle(int x) { _pickles.Add(_pickleFactory.MakePickle(x)); } public void GetObjectData(SerializationInfo info, StreamingContext context) {
Please note that Bar has its own factory and pickles collection. Here's the problem: when the Bar deserialization constructor is called, I have no way to get it another PickleFactory. The original PickleFactory was provided by Bar BarFactory, but the deserialization constructor was not called by BarFactory.
My current plan for solving this problem would be to extract all the serializable Bar elements into the BarDataObject native class. Then I would make BarDataObject serializable, but not Bar itself. I would add the BarFactory function, which takes the BarDataObject parameter as a parameter and creates a panel to populate all the information from the BarDataObject.
However, suppose Pickle also has the service classes that it received from the factory that made it, which is also impossible to serialize. So I would have to extract the DataObject from Pickle, and my BarDataObject would have to hold the PickleDataObject file. And suppose Pickle had a member variable with a set of data and services? I would have to create and maintain a DataObject for this. This seems like a real bummer, especially considering that there are many other things in my project that I need to serialize, and they are likely to run into the same problem.
So is there a better solution? Am I doing something wrong, DI-wise? I just started working with DI and Ninject, but I canβt find anyone to come up with a good way to serialize objects that have been introduced by service classes.
c # dependency-injection serialization ninject
tandersen
source share