Skip to content

Fixes incorrect service resolution in Development environment - #68053

Closed
maryamariyan wants to merge 3 commits into
dotnet:mainfrom
maryamariyan:di-debug
Closed

maryamariyan wants to merge 3 commits into
dotnet:mainfrom
maryamariyan:di-debug

Conversation

@maryamariyan

@maryamariyan maryamariyan commented Apr 14, 2022 •

Copy link
Copy Markdown
Contributor

Today, if the service type is generic (constrained or not) ValidateService would cause a bug and incorrectly resolve the generics.


Debug notes

Given:

        public interface IAA { }
        public interface IBB<T> { }
        public class AA : IAA { }
        public class BB : IBB<AA> { }
        public class GenericBB<T> : IBB<T> { }
        public class ConstrainedGenericBB<T> : IBB<T> where T : IAA { }

When BuildServiceProvider gets called for:

            services.AddTransient<IBB<AA>, BB>();
            services.AddTransient(typeof(IBB<>), typeof(ConstrainedGenericBB<>));
            var serviceProvider = services.BuildServiceProvider(new ServiceProviderOptions() { ValidateOnBuild = true });

ValidateOnBuild makes CallSiteFactory store some service call sites into _callSiteCache.

Currently because of the if condition:

private void ValidateService(ServiceDescriptor descriptor)
{
if (descriptor.ServiceType.IsGenericType && !descriptor.ServiceType.IsConstructedGenericType)
{
return;
}
try
{
ServiceCallSite? callSite = CallSiteFactory.GetCallSite(descriptor, new CallSiteChain());

for the first transient descriptor a cache item gets created for IBB<AA> in _callSiteCache, but skips to add another cache item for IBB<> to with implementation type ConstrainedGenericBB.

Then when we call

serviceProvider.GetServices<IBB<AA>>()

DI thinks it already has all the cache info it needs to resolve this and resolves twice with the one cache item rather than also resolving with ConstrainedGenericBB.


Proposed fix

I think the expectation and fix here should be to skip ValidateOnBuild on generics. We already have the test below expecting ValidateOnBuild to be skipped for generics anyway, so that makes me more convinced that this is the fix we want for the reported bug:

[Fact]
public void BuildServiceProvider_ValidateOnBuild_SkipsOpenGenerics()
{
// Arrange
var serviceCollection = new ServiceCollection();
serviceCollection.AddTransient(typeof(IFakeOpenGenericService<>), typeof(FakeOpenGenericService<>));
// Act + Assert
serviceCollection.BuildServiceProvider(new ServiceProviderOptions() { ValidateOnBuild = true });
}

When we recently added more support for generic service resolution (open generics), we missed out on testing it with ValidateOnBuild. PR that added support for constrained open generics: #39540

This bug fix helps properly resolve IEnumerable<> services set with ValidateOnBuild using GetServices when dealing with constrained open generics.

Fixes #65145

cc @jbogard

@ghost

ghost commented Apr 14, 2022

Copy link
Copy Markdown

Tagging subscribers to this area: @dotnet/area-extensions-dependencyinjection
See info in area-owners.md if you want to be subscribed.

Issue Details
  • Fixes a ValidateOnBuild bug to properly resolve IEnumerable<> services using GetServices when dealing with constrained open generics.

PR that added support for constrained open generics: #39540

cc @jbogard

Author: maryamariyan
Assignees: maryamariyan
Labels:

area-Extensions-DependencyInjection

Milestone: -

- Fixed ValidateOnBuild to properly resolve constrained open generics

private void ValidateService(ServiceDescriptor descriptor)
{
if (descriptor.ServiceType.IsGenericType && !descriptor.ServiceType.IsConstructedGenericType)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IsConstructedGenericType

@maryamariyan could you explain more about this change?

From the code I think when having IsConstructedGenericType should try to Get or create the callsite? for IEnumerable<>, maybe need to check for interfaces instead?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Adding a comment to the code might be a good idea.

@maryamariyan maryamariyan Apr 18, 2022 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What I noticed is if the type is generic (constrained or not) ValidateService would incorrectly resolve the generics.

Also since we already have the test below expecting ValidateOnBuild to be skipped for generics, then I'm more convinced this is the fix we want for the reported bug.

[Fact]
public void BuildServiceProvider_ValidateOnBuild_SkipsOpenGenerics()
{
// Arrange
var serviceCollection = new ServiceCollection();
serviceCollection.AddTransient(typeof(IFakeOpenGenericService<>), typeof(FakeOpenGenericService<>));
// Act + Assert
serviceCollection.BuildServiceProvider(new ServiceProviderOptions() { ValidateOnBuild = true });
}

Added comment:

// Skip validation for generic service types

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a breaking change right? Now closed generics won't be validated?

@maryamariyan

maryamariyan commented Apr 19, 2022 •

Copy link
Copy Markdown
Contributor Author

Here's some more info for review:

  • The problem happens during BuildServiceProvider when trying to do ValidateService on generic types.
  • Since we skip for open generics at this stage, then the set of call site caches will be incomplete once BuildServiceProvider is finished
  • Then later when we try getting IEnumerable service, we expect all caches and slots to align but they won't because we dont have all in _callSiteCache.

what would work is to either not add cache callsites at all during validate, or place them at the right slot as we add them.

To mitigate this, another approach I tried was to replace the already inserted cache if the implementation type does not match the descriptor implementation type. but this approach would fail for singletons. (Refer to commit 5dde8ce).

I will look to see if we can do better.

@maryamariyan

maryamariyan commented Apr 19, 2022 •

Copy link
Copy Markdown
Contributor Author

I still dont think the existing PR I have is incorrect per say, the downside is that we no longer validate for generics.

I think my current fix should still be fine. this caching bug would only happen when we are validating on build with open generics available in descriptor list.

the fact that with validate we are skipping some descriptors (the open generic ones) means that if we are in fact later adding the rest in the callSiteCache the ORDER will become messed up for the ones we add later (and not coherent with the descriptor list).

and if we are to validate but not add to cache, then for singletons we would be loosing the singleton instance if we don't add to cache.

thoughts?

maybe a midway compromise is to allow validate generics to happen only for transient ones, but I wouldnt like special casing the validation scenario this way.

@eerhardt

Copy link
Copy Markdown
Member

the downside is that we no longer validate for generics.

Is this acceptable behavior? Why is it OK to no longer validate constructed generic services?

@maryamariyan

Copy link
Copy Markdown
Contributor Author

Why is it OK to no longer validate constructed generic services?

I think when we also have open generics registered, validating constructed generics will mess with the slot ordering, unless we had a separate cache for open generics to identify slots on but might be a bigger fix than we want

@eerhardt eerhardt left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we've been through all the possible solutions to this problem, and skipping validation seems to be the only viable solution.

I'm OK with moving forward with this change to get the scenario working correctly. @davidfowl - any concerns?

private void ValidateService(ServiceDescriptor descriptor)
{
if (descriptor.ServiceType.IsGenericType && !descriptor.ServiceType.IsConstructedGenericType)
// Skip validation for generic service types

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should add more description here explaining why we are skipping validation for generic service types.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

add a commit to address this

@davidfowl davidfowl left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I need to do one more pass.

@ghost ghost added the needs-author-action An issue or pull request that requires more info or actions from the author. label May 24, 2022
@ghost ghost added the no-recent-activity label Jun 7, 2022
@ghost

ghost commented Jun 7, 2022

Copy link
Copy Markdown

This pull request has been automatically marked no-recent-activity because it has not had any activity for 14 days. It will be closed if no further activity occurs within 14 more days. Any new comment (by anyone, not necessarily the author) will remove no-recent-activity.

@ghost ghost removed the no-recent-activity label Jun 8, 2022
@maryamariyan

Copy link
Copy Markdown
Contributor Author

Reviewed this PR with @davidfowl late last week and here's a summary to it:

  • The fix in this PR is a breaking change so we'd want to consider an alternative approach to it.
  • We found another fix would be to get the callsite in a different way ServiceProvider.ValidateService(..) rather than skipping validation for generic types:
-ServiceCallSite? callSite = CallSiteFactory.GetCallSite(descriptor, new CallSiteChain());
+ServiceCallSite? callSite = CallSiteFactory.GetCallSite(typeof(IEnumerable<>).MakeGenericType(descriptor.ServiceType), new CallSiteChain());

@ghost ghost removed the needs-author-action An issue or pull request that requires more info or actions from the author. label Jun 20, 2022
@ghost ghost locked as resolved and limited conversation to collaborators Jul 20, 2022
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Services resolving incorrectly in Development environment but not Production

4 participants