Skip to content

Commit

Permalink
Use DryIoCs ResolveManyBehavior.AsFixedArray to prevent dependencies …
Browse files Browse the repository at this point in the history
…from being created twice (#891)

Co-authored-by: David Scheidt <david.scheidt@humotion.net>
  • Loading branch information
scheidtdav and scheidtdav authored Mar 25, 2022
1 parent a7315fe commit 83fcf5f
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 3 deletions.
24 changes: 24 additions & 0 deletions src/Splat.DryIoc.Tests/DependencyResolverTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -266,5 +266,29 @@ public void DryIocDependencyResolver_Should_Resolve_AfterDuplicateKeyedRegistrat

vmOne.Should().NotBeNull();
}

/// <summary>
/// DryIoc dependency resolver should create a resolved object only once when resolving.
/// </summary>
[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<ViewModelOne>()
var vms = resolver.GetServices(typeof(ViewModelOne));
count.Should().Be(1);
var vmOne = vms.LastOrDefault();
vmOne.Should().NotBeNull();
count.Should().Be(1);
}
}
}
6 changes: 3 additions & 3 deletions src/Splat.DryIoc/DryIocDependencyResolver.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,19 +43,19 @@ public virtual IEnumerable<object> 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);
}

/// <inheritdoc />
Expand Down

0 comments on commit 83fcf5f

Please sign in to comment.