I am having an issue with Blazor Server .NET 8 and Dependency Injection. The problem I am encountering involves an IClaimsTransformation that is used to populate additional identities to a user after successful login. This IClaimsTransformation is registered with the DI framework as Scoped.
Inside the IClaimsTransformation, I have created a class to help manage state, ApplicationState. This class is also registered as Scoped.
The issue is that when the application starts, the IClaimsTransformation constructor is being called multiple times (about half a dozen). During these calls, ApplicationState is being instantiated the same number of times, causing the original state of the application to be overridden each time. I added a Guid named Instance in the ApplicationState class, which gets set to a new Guid during the constructor, and confirmed that a new instance is created every time the IClaimsTransformation is called.
Here is my setup:
Program.cs
builder.Services.AddScoped<IClaimsTransformation, UserContextClaimsTransformation>();
builder.Services.AddScoped<ApplicationState>();
IClaimsTransformation Implementation
public class UserContextClaimsTransformation : IClaimsTransformation
{
private readonly pgService _pgService;
private readonly Services.IdentityService _identityService;
private readonly ApplicationState _applicationState;
public UserContextClaimsTransformation(pgService pgService, Services.IdentityService identityService, ApplicationState applicationState)
{
_pgService = pgService;
_identityService = identityService;
_applicationState = applicationState;
}
}
ApplicationState Class
public class ApplicationState
{
private Experience _currentExperience;
private List<Experience> _availableExperiences;
public Guid Instance { get; private set; }
public ApplicationState()
{
Instance = Guid.NewGuid();
}
}
What am I doing wrong here? Why is IClaimsTransformation being instantiated multiple times, and how can I ensure that ApplicationState maintains a consistent state throughout the application?
Any help would be greatly appreciated. Thank you.