Hello Dear Readers,
As Analog Devices GUI Team, we had a great event this Tuesday. We wrote a Web API that can change its behavior at run-time according to a flag.
As a team, we loved this event and called it a mini-hackathon.
We first understood the problem in the morning. Our problem is as follows: We will write a Web API This API will have an endpoint called getweather. This endpoint will generate three types of random weather reports. Celsius, Fahrenheit and Kelvin. It will decide the type of calculation according to the flag set in the runtime.
{
public interface IWeatherOperation
{
IEnumerable<WeatherForecast> GetWeather(string temperatureType);
}
namespace
FeatureFlaggingDotNet.FeatureFlagging.Domain.Services
{
public class CelsiusOperations : IWeatherOperation
{
public
IEnumerable<WeatherForecast> GetWeather(string temperatureType)
{
return
Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date =
DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
Temperature =
(Random.Shared.Next(-20, 55)).ToString() + " " + temperatureType,
Summary =
WeatherTypes.Summaries[Random.Shared.Next(WeatherTypes.Summaries.Length)]
})
.ToArray();
}
}
}
namespace
FeatureFlaggingDotNet.FeatureFlagging.Domain
{
public class WeatherFactory
{
private readonly IServiceProvider serviceProvider;
public WeatherFactory(IServiceProvider serviceProvider)
{
this.serviceProvider
= serviceProvider;
}
public
IWeatherOperation WeatherOperation(string userSelection)
{
return userSelection.ToLower() switch
{
"celsius" => (IWeatherOperation)serviceProvider.GetService(typeof(CelsiusOperations)),
"fahrenheit" => (IWeatherOperation)serviceProvider.GetService(typeof(FahrenheitOperations)),
"kelvin" => (IWeatherOperation)serviceProvider.GetService(typeof(KelvinOperations)),
_ => throw new NotImplementedException(),
};
}
}
}
builder.Services.AddSingleton<IFeatureFlagging,
FeatureFlagging>();
builder.Services.AddSingleton<WeatherFactory>();
builder.Services.AddSingleton<CelsiusOperations>()
.AddSingleton<IWeatherOperation, CelsiusOperations>(s =>
s.GetService<CelsiusOperations>());
builder.Services.AddSingleton<FahrenheitOperations>()
.AddSingleton<IWeatherOperation, FahrenheitOperations>(s =>
s.GetService<FahrenheitOperations>());
builder.Services.AddSingleton<KelvinOperations>()
.AddSingleton<IWeatherOperation, KelvinOperations>(s => s.GetService<KelvinOperations>());
var app = builder.Build();
Hiç yorum yok:
Yorum Gönder