views:

123

answers:

4

If a program has literally just deserialized an object (doesn't really matter how, but just say BinaryFormatter was used).

What is a good design to use for re-injecting the dependencies of this object?

Is there a common pattern for this?

I suppose I would need to wrap the Deserialize() method up to act as a factory inside the container.

Thanks!

A: 

I would use the OnDeserialized attribute to point at a method that would do the re-injection.

Tom Cabanski
But that would surely require a dependency upon the container itself i.e. breaking the golden IoC rule?
NathanE
Not true if you are using something like Microsoft.Practices.ServiceLocation you are container-neutral.
Tom Cabanski
Container-neutral, but still dependent on the container.
Jeff Sternal
You could use a static class and send the object there, the method on that class would take of the injection then.
Femaref
A: 

Since the dependencies were not serialized themselves, I assume their state is independent of the state of the deserialized object. You might therefore simply re-inject the dependencies by providing properties for them which would be called immediately after the call to "Deserialize".

Seventh Element
A: 

Unity has a concept of "BuildUp" where you can ask it to fulfil the dependencies of an existing object. I don't know if autofac (which I presume you are using from the tags) has an equivalent.

Mark Heath
Property injection is the Autofac equvivalent
Peter Lillevold
+7  A: 

You shouldn't serialize objects with dependencies that can't themselves be serialized.

Instead, split it into two classes: extract the serializable parts into a separate class.

After deserializing, you can associate the resulting object with an instance of the original class (the one with dependencies).

Jeff Sternal
"All problems in computer science can be solved by another level of indirection, except for the problem of too many layers of indirection."
Fábio Batista
I think of my suggestion as *removing* a layer of indirection. (Or at least removing the need for an additional one!) ;)
Jeff Sternal
Have to admit Jeff, this was a possible solution that crossed the back of my mind. I have implemented it now and the codebase is better for it :)
NathanE