Created
December 8, 2025 14:12
-
-
Save sunmeat/0bfbc36a5c60b8bd8cbf52dbcb4477b3 to your computer and use it in GitHub Desktop.
IoC-контейнер ASP.NET Core
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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