Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

AsyncState breaks when used in multiple service collections #4959

Closed
xakep139 opened this issue Feb 20, 2024 · 1 comment · Fixed by #4966
Closed

AsyncState breaks when used in multiple service collections #4959

xakep139 opened this issue Feb 20, 2024 · 1 comment · Fixed by #4966
Assignees
Labels
area-fundamentals bug This issue describes a behavior which is not expected - a bug. work in progress 🚧

Comments

@xakep139
Copy link
Contributor

xakep139 commented Feb 20, 2024

Description

Current implementation of AsyncState has both its pool and AsyncLocal as static fields, but the counter isn't static:

This counter is used to generate indexes of IAsyncContexts, thus when used within different service collections, it start to pointing to items that were added previously (and they have different types potentially).

Reproduction Steps

using Microsoft.Extensions.AsyncState;
using Microsoft.Extensions.DependencyInjection;

await using var spOne = PrepareAsyncState(new Tuple<double>(3.14));
await using var spTwo = PrepareAsyncState(new Tuple<int>(42));

// This line throws:
_ = spOne.GetRequiredService<IAsyncContext<Tuple<double>>>().Get();

static ServiceProvider PrepareAsyncState<T>(T value)
	where T : notnull
{
	var services = new ServiceCollection().AddAsyncState().BuildServiceProvider();
	services.GetRequiredService<IAsyncState>().Initialize();
	services.GetRequiredService<IAsyncContext<T>>().Set(value);
	return services;
}

Expected behavior

Code doesn't throw.

Actual behavior

The code throws InvalidCastException.

Regression?

No

Known Workarounds

No response

Configuration

No response

Other information

Related discussion exists regarding the IHttpContextAccessor: aspnet/HttpAbstractions#753

@xakep139 xakep139 added untriaged bug This issue describes a behavior which is not expected - a bug. labels Feb 20, 2024
@xakep139
Copy link
Contributor Author

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
area-fundamentals bug This issue describes a behavior which is not expected - a bug. work in progress 🚧
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants