Skip to content

Instantly share code, notes, and snippets.

@ragavendra
Created June 4, 2024 22:02
Show Gist options
  • Save ragavendra/409a2a1acae58fb793868039e5dc537a to your computer and use it in GitHub Desktop.
Save ragavendra/409a2a1acae58fb793868039e5dc537a to your computer and use it in GitHub Desktop.
Dotnet new webapi project Dependency Injection
using webapi;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
// builder.Services.AddSingleton<ISampleInterface, SampleClass>();
// builder.Services.AddTransient<ISampleInterface, SampleClass>();
builder.Services.AddScoped<ISampleInterface, SampleClass>();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
var summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
app.MapGet("/weatherforecast", (ISampleInterface isampleInterfae) =>
{
var forecast = Enumerable.Range(1, 5).Select(index =>
new WeatherForecast
(
DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
Random.Shared.Next(-20, 55),
summaries[Random.Shared.Next(summaries.Length)] + isampleInterfae.Name
))
.ToArray();
return forecast;
})
.WithName("GetWeatherForecast")
.WithOpenApi();
app.Run();
record WeatherForecast(DateOnly Date, int TemperatureC, string? Summary)
{
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
}
public interface ISampleInterface
{
public string Name { get; set; }
public int Id { get; set; }
}
public class SampleClass : ISampleInterface
{
public string Name { get; set; }
// public int Id { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
public int Id { get; set; }
// public SampleClass(string name) {
public SampleClass() {
Name = DateTime.Now.ToString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment