← Барлық мақалаларға оралу

.NET-та IFeatureManager арқылы Feature Flags

Жарияланды

Microsoft.FeatureManagement package ішіндегі IFeatureManager .NET-та feature flags басқарады.

Ол application running кезінде right branch of logic таңдауға мүмкіндік береді.

Feature Flags қай жерде пайдалы

  • Feature-ді temporarily enable немесе quickly disable ету, мысалы new release немесе hotfix кезінде.

  • Failures кезінде problematic functionality disable ету.

  • A/B tests іске қосу.

  • Promotions сияқты temporary scenarios support ету.

Қалай жұмыс істейді

Feature Management-ті dependency injection container ішіне register етіп, қажет болса filters қосыңыз. Мысалы, TimeWindowFilter flag-ты only specific time range ішінде activates етеді.

using Microsoft.FeatureManagement;
using Microsoft.FeatureManagement.FeatureFilters;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddFeatureManagement()
    // If you need a time window filter, add the following line
    .AddFeatureFilter<TimeWindowFilter>();

builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new()
    {
        Title = "Feature Flags Demo API",
        Version = "v1"
    });
});

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.MapControllers();

app.Run();

Flags-ты appsettings.json ішінде configure ету

Feature flag values appsettings.json ішінде set етіңіз:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "FeatureManagement": {
    "NewDashboard": true,
    "HolidayPromo": {
      "EnabledFor": [
        {
          "Name": "TimeWindow",
          "Parameters": {
            "Start": "2024-12-01T00:00:00Z",
            "End": "2025-12-31T23:59:59Z"
          }
        }
      ]
    }
  }
}

IFeatureManager арқылы flag тексеру

IFeatureManager inject жасап, IsEnabledAsync шақыру арқылы flag state тексеріңіз:

using Microsoft.AspNetCore.Mvc;
using Microsoft.FeatureManagement;

namespace FeatureFlagsDemo.Api.Controllers;

[ApiController]
[Route("api/[controller]")]
public class DashboardController(IFeatureManager featureManager) : ControllerBase
{
    [HttpGet]
    public async Task<IActionResult> GetDashboard()
    {
        var useNewDashboard =
            await featureManager.IsEnabledAsync("NewDashboard");

        if (useNewDashboard)
        {
            return Ok(new
            {
                Version = "New",
                Data = GetNewDashboardData(),
            });
        }

        return Ok(new
        {
            Version = "Legacy",
            Data = GetLegacyDashboardData(),
        });
    }

    [HttpGet("promo")]
    public async Task<IActionResult> GetHolidayPromo()
    {
        if (!await featureManager.IsEnabledAsync("HolidayPromo"))
        {
            return Ok(new { Message = "No active promotions" });
        }

        return Ok(new
        {
            Message = "Holiday Special Offer!",
            Discount = "50% OFF",
            ValidUntil = "December 31, 2025",
            PromoCode = "HOLIDAY2025"
        });
    }

    private static object GetNewDashboardData() => new
    {
        Charts = new[]
        {
            new { Name = "Revenue Chart", Type = "Line", Interactive = true },
            new { Name = "User Activity", Type = "Heatmap", Interactive = true },
            new { Name = "Performance Metrics", Type = "Gauge", Interactive = true }
        },
        Layout = "Modern Grid",
        Theme = "Dark Mode Available",
        Features = new[]
        {
            "Real-time Updates",
            "Custom Widgets",
            "Export Options"
        }
    };

    private static object GetLegacyDashboardData() => new
    {
        Charts = new[]
        {
            new { Name = "Basic Revenue", Type = "Bar", Interactive = false },
            new { Name = "Simple Stats", Type = "Table", Interactive = false }
        },
        Layout = "Classic List",
        Theme = "Light Only",
        Features = new[] { "Static Reports" }
    };
}

Нәтижесінде application behavior-ды redeploy жасамай configuration арқылы өзгертуге болады.

Бұл approach time saves етеді, release errors risk азайтады және team-ге production ішінде functionality үстінен көбірек control береді.