Skip to content

Refactor PlayerService to use IHostEnvironment instead of Environment.GetEnvironmentVariable #320

@nanotaboada

Description

@nanotaboada

Description

Refactor PlayerService to use the ASP.NET Core recommended IHostEnvironment interface for environment detection instead of directly accessing environment variables via Environment.GetEnvironmentVariable.

Current Implementation

PlayerService currently checks the environment using:

if (Environment.GetEnvironmentVariable(AspNetCore_Environment) == Development)
{
    await SimulateRepositoryDelayAsync();
}

This approach:

  • Uses string-based comparison (prone to typos)
  • Requires manual constant definitions for environment variable name and value
  • Is less idiomatic for ASP.NET Core applications

Proposed solution

Inject IHostEnvironment and use the built-in helper method:

public class PlayerService(
    IPlayerRepository playerRepository,
    ILogger<PlayerService> logger,
    IMemoryCache memoryCache,
    IMapper mapper,
    IHostEnvironment environment  // Add this
) : IPlayerService
{
    // Replace line 71 with:
    if (environment.IsDevelopment())
    {
        await SimulateRepositoryDelayAsync();
    }
}

Benefits

  • Type-safe: Uses strongly-typed methods instead of string comparisons
  • Cleaner code: Removes need for AspNetCore_Environment and Development constants
  • Consistent: Aligns with ExceptionMiddleware implementation (see Add custom middleware for global exception handling #184)
  • Best practice: Follows ASP.NET Core recommended patterns
  • Built-in helpers: Access to IsDevelopment(), IsProduction(), IsStaging()

Acceptance Criteria

  • Inject IHostEnvironment into PlayerService constructor
  • Replace Environment.GetEnvironmentVariable(AspNetCore_Environment) == Development with environment.IsDevelopment()
  • Remove unused constants: AspNetCore_Environment and Development
  • Verify all existing unit tests still pass
  • Update PlayerServiceTests if needed to mock IHostEnvironment

References

Labels

  • enhancement - Code improvement
  • refactor - Code refactoring
  • good first issue - Straightforward refactoring task
  • .NET - .NET code changes

Metadata

Metadata

Assignees

No one assigned

    Labels

    .NETPull requests that update .NET codeenhancementNew feature or requestgood first issueGood for newcomers

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions