From 77bc232209e91afe9717034189f05a08f88b3289 Mon Sep 17 00:00:00 2001 From: Benedikt Reinartz Date: Tue, 21 Oct 2025 19:20:12 +0200 Subject: [PATCH] Properly detect availability of BinaryFormatter (#2639) (cherry picked from commit 0258688e684c0a7ad59b4d76384a1d4a21735472) --- src/runtime/StateSerialization/RuntimeData.cs | 33 +++++++++++++++++-- 1 file changed, 31 insertions(+), 2 deletions(-) diff --git a/src/runtime/StateSerialization/RuntimeData.cs b/src/runtime/StateSerialization/RuntimeData.cs index 20d9e2e8a..0f1e8b460 100644 --- a/src/runtime/StateSerialization/RuntimeData.cs +++ b/src/runtime/StateSerialization/RuntimeData.cs @@ -17,7 +17,36 @@ namespace Python.Runtime { public static class RuntimeData { - private static Type? _formatterType; + + public readonly static Func DefaultFormatterFactory = () => + { + try + { + var res = new BinaryFormatter(); + res.Serialize(new MemoryStream(), 1); // test if BinaryFormatter is usable + return res; + } + catch + { + return new NoopFormatter(); + } + }; + + private static Func _formatterFactory { get; set; } = DefaultFormatterFactory; + + public static Func FormatterFactory + { + get => _formatterFactory; + set + { + if (value == null) + throw new ArgumentNullException(nameof(value)); + + _formatterFactory = value; + } + } + + private static Type? _formatterType = null; public static Type? FormatterType { get => _formatterType; @@ -206,7 +235,7 @@ internal static IFormatter CreateFormatter() { return FormatterType != null ? (IFormatter)Activator.CreateInstance(FormatterType) - : new BinaryFormatter(); + : FormatterFactory(); } } }