Skip to content

Instantly share code, notes, and snippets.

@sunmeat
Created December 8, 2025 14:12
Show Gist options
  • Select an option

  • Save sunmeat/0bfbc36a5c60b8bd8cbf52dbcb4477b3 to your computer and use it in GitHub Desktop.

Select an option

Save sunmeat/0bfbc36a5c60b8bd8cbf52dbcb4477b3 to your computer and use it in GitHub Desktop.
IoC-контейнер ASP.NET Core
using Microsoft.EntityFrameworkCore;
namespace mvc
{
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
string? connection = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<StudentContext>(options => options.UseSqlServer(connection));
builder.Services.AddControllersWithViews();
var app = builder.Build();
////////////////////////////////////////////////////////////////////////////////////
// 1. створюємо штучний HTTP-запит (Scope)
using var scope = app.Services.CreateScope();
// 2. беремо з цього запиту справжній IoC-контейнер
var context = scope.ServiceProvider.GetRequiredService<StudentContext>();
// 3. переконуємося, що все працює
Console.WriteLine("!!! SUCCESS !!!");
Console.WriteLine($"Students count: {context.Students.Count()}");
Console.WriteLine($"Hash code: {context.GetHashCode()}");
////////////////////////////////////////////////////////////////////////////////////
app.UseStaticFiles();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Student}/{action=Index}/{id?}");
app.Run();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment