static Packet() { surrogateSelector = new SurrogateSelector(); streamingContext = new StreamingContext(StreamingContextStates.All); // Our surrogates can be safely used in every context. IEnumerable <Type> types = AppDomain.CurrentDomain.GetAssemblies() .SelectMany(a => a.GetTypes() .Where(t => t.BaseType != null && t.BaseType.IsGenericType && t.BaseType.GetGenericTypeDefinition() == typeof(SerializationSurrogate <>) && t.IsClass && !t.IsAbstract)); foreach (Type type in types) { ISerializationSurrogate surrogate = (ISerializationSurrogate)Activator.CreateInstance(type); Type surrogatedType = type.BaseType.GetGenericArguments()[0]; surrogateSelector.AddSurrogate(surrogatedType, streamingContext, surrogate); Log.Debug("Added surrogate " + surrogate.GetType().Name + " for type " + surrogatedType); } // For completeness, we could pass a StreamingContextStates.CrossComputer. serializer = new BinaryFormatter(surrogateSelector, streamingContext); }
private void FixupSpecialObject(ObjectHolder holder) { ISurrogateSelector selector = null; if (holder.HasSurrogate) { ISerializationSurrogate surrogate = holder.Surrogate; object obj = surrogate.SetObjectData(holder.ObjectValue, holder.SerializationInfo, this.m_context, selector); if (obj != null) { if (!holder.CanSurrogatedObjectValueChange && obj != holder.ObjectValue) { throw new SerializationException(string.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("Serialization_NotCyclicallyReferenceableSurrogate"), surrogate.GetType().FullName)); } holder.SetObjectValue(obj, this); } holder.m_surrogate = null; holder.SetFlags(); } else { this.CompleteISerializableObject(holder.ObjectValue, holder.SerializationInfo, this.m_context); } holder.SerializationInfo = null; holder.RequiresSerInfoFixup = false; if (holder.RequiresValueTypeFixup && holder.ValueTypeFixupPerformed) { this.DoValueTypeFixup(null, holder, holder.ObjectValue); } this.DoNewlyRegisteredObjectFixups(holder); }