diff --git a/src/ImageSharp/Configuration.cs b/src/ImageSharp/Configuration.cs index 818fb8193c..574a6912fd 100644 --- a/src/ImageSharp/Configuration.cs +++ b/src/ImageSharp/Configuration.cs @@ -126,7 +126,7 @@ namespace SixLabors.ImageSharp /// /// Gets or sets the that is currently in use. /// - public MemoryAllocator MemoryAllocator { get; set; } = MemoryAllocator.Create(); + public MemoryAllocator MemoryAllocator { get; set; } = MemoryAllocator.Default; /// /// Gets the maximum header size of all the formats. diff --git a/src/ImageSharp/Memory/Allocators/MemoryAllocator.cs b/src/ImageSharp/Memory/Allocators/MemoryAllocator.cs index ec0771a485..d9ebb7cb95 100644 --- a/src/ImageSharp/Memory/Allocators/MemoryAllocator.cs +++ b/src/ImageSharp/Memory/Allocators/MemoryAllocator.cs @@ -11,6 +11,27 @@ namespace SixLabors.ImageSharp.Memory /// public abstract class MemoryAllocator { + private static MemoryAllocator defaultMemoryAllocator = Create(); + + /// + /// Gets or sets the default global instance for the current process. + /// + /// + /// Since is lazy-initialized, setting the value of + /// will only override 's + /// before the first read of the property. + /// After that, a manual assigment of is necessary. + /// + public static MemoryAllocator Default + { + get => defaultMemoryAllocator; + set + { + Guard.NotNull(value, nameof(Default)); + defaultMemoryAllocator = value; + } + } + /// /// Gets the length of the largest contiguous buffer that can be handled by this allocator instance in bytes. /// diff --git a/tests/ImageSharp.Tests/ConfigurationTests.cs b/tests/ImageSharp.Tests/ConfigurationTests.cs index 3ad8ef2f8a..cabe15cb6e 100644 --- a/tests/ImageSharp.Tests/ConfigurationTests.cs +++ b/tests/ImageSharp.Tests/ConfigurationTests.cs @@ -3,10 +3,12 @@ using System; using System.Linq; +using Microsoft.DotNet.RemoteExecutor; using Moq; using SixLabors.ImageSharp.Formats.Bmp; using SixLabors.ImageSharp.IO; - +using SixLabors.ImageSharp.Memory; +using SixLabors.ImageSharp.Tests.Memory; using Xunit; // ReSharper disable InconsistentNaming @@ -146,5 +148,33 @@ namespace SixLabors.ImageSharp.Tests Assert.Throws( () => config.StreamProcessingBufferSize = 0); } + + [Fact] + public void InheritsDefaultMemoryAllocatorInstance() + { + RemoteExecutor.Invoke(RunTest).Dispose(); + + static void RunTest() + { + MemoryAllocator allocator = new TestMemoryAllocator(); + MemoryAllocator.Default = allocator; + + var c1 = new Configuration(); + var c2 = new Configuration(new MockConfigurationModule()); + var c3 = Configuration.CreateDefaultInstance(); + + Assert.Same(allocator, Configuration.Default.MemoryAllocator); + Assert.Same(allocator, c1.MemoryAllocator); + Assert.Same(allocator, c2.MemoryAllocator); + Assert.Same(allocator, c3.MemoryAllocator); + } + } + + private class MockConfigurationModule : IConfigurationModule + { + public void Configure(Configuration configuration) + { + } + } } }