From 83fcf5f66835e00ef7600af7b0d4769d26f24cf6 Mon Sep 17 00:00:00 2001 From: David Scheidt Date: Fri, 25 Mar 2022 10:27:16 +0100 Subject: [PATCH] Use DryIoCs ResolveManyBehavior.AsFixedArray to prevent dependencies from being created twice (#891) Co-authored-by: David Scheidt --- .../DependencyResolverTests.cs | 24 +++++++++++++++++++ src/Splat.DryIoc/DryIocDependencyResolver.cs | 6 ++--- 2 files changed, 27 insertions(+), 3 deletions(-) diff --git a/src/Splat.DryIoc.Tests/DependencyResolverTests.cs b/src/Splat.DryIoc.Tests/DependencyResolverTests.cs index afb8a5f70..774fbee7a 100644 --- a/src/Splat.DryIoc.Tests/DependencyResolverTests.cs +++ b/src/Splat.DryIoc.Tests/DependencyResolverTests.cs @@ -266,5 +266,29 @@ public void DryIocDependencyResolver_Should_Resolve_AfterDuplicateKeyedRegistrat vmOne.Should().NotBeNull(); } + + /// + /// DryIoc dependency resolver should create a resolved object only once when resolving. + /// + [Fact] + public void DryIocDependencyResolver_Should_Create_Once_When_Resolving() + { + var container = new Container(); + var count = 0; + container.RegisterDelegate(() => + { + count++; + return new ViewModelOne(); + }); + + var resolver = new DryIocDependencyResolver(container); + + // Imitate a call to Locator.Current.GetService() + var vms = resolver.GetServices(typeof(ViewModelOne)); + count.Should().Be(1); + var vmOne = vms.LastOrDefault(); + vmOne.Should().NotBeNull(); + count.Should().Be(1); + } } } diff --git a/src/Splat.DryIoc/DryIocDependencyResolver.cs b/src/Splat.DryIoc/DryIocDependencyResolver.cs index f03b22b94..0237d3d3c 100644 --- a/src/Splat.DryIoc/DryIocDependencyResolver.cs +++ b/src/Splat.DryIoc/DryIocDependencyResolver.cs @@ -43,19 +43,19 @@ public virtual IEnumerable GetServices(Type? serviceType, string? contra } var key = (serviceType, contract ?? string.Empty); - var registeredinSplat = _container.ResolveMany(serviceType, serviceKey: key).Select(x => isNull ? ((NullServiceType)x).Factory()! : x); + var registeredinSplat = _container.ResolveMany(serviceType, behavior: ResolveManyBehavior.AsFixedArray, serviceKey: key).Select(x => isNull ? ((NullServiceType)x).Factory()! : x); if (registeredinSplat.Any()) { return registeredinSplat; } - var registeredWithContract = _container.ResolveMany(serviceType, serviceKey: contract).Select(x => isNull ? ((NullServiceType)x).Factory()! : x); + var registeredWithContract = _container.ResolveMany(serviceType, behavior: ResolveManyBehavior.AsFixedArray, serviceKey: contract).Select(x => isNull ? ((NullServiceType)x).Factory()! : x); if (registeredWithContract.Any()) { return registeredWithContract; } - return _container.ResolveMany(serviceType).Select(x => isNull ? ((NullServiceType)x).Factory()! : x); + return _container.ResolveMany(serviceType, behavior: ResolveManyBehavior.AsFixedArray).Select(x => isNull ? ((NullServiceType)x).Factory()! : x); } ///