From be194688bd520df2bef419001d7e781e88b72a37 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Boris=20Mila=C5=A1inovi=C4=87?= Date: Mon, 20 Apr 2026 20:28:54 +0200 Subject: [PATCH] DI Setup using HostApplicationBuilder --- DataAccess/EF_Demo/DISetup.cs | 37 ++++++++----------- DataAccess/EF_Demo/Demo.cs | 35 ++++++++---------- DataAccess/EF_Demo/EF_Demo.csproj | 4 +- DataAccess/EF_Demo/Program.cs | 15 ++++---- .../EF_Demo/Properties/launchSettings.json | 10 +++++ DataAccess/EF_Demo/appsettings.json | 2 +- 6 files changed, 53 insertions(+), 50 deletions(-) create mode 100644 DataAccess/EF_Demo/Properties/launchSettings.json diff --git a/DataAccess/EF_Demo/DISetup.cs b/DataAccess/EF_Demo/DISetup.cs index 24927b1..39d8df6 100644 --- a/DataAccess/EF_Demo/DISetup.cs +++ b/DataAccess/EF_Demo/DISetup.cs @@ -1,32 +1,27 @@ -using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace EF_Demo; -internal class DISetup +internal static class DISetup { - public static ServiceProvider BuildDI() + public static IHost BuildHost(string[] args) { - var configuration = new ConfigurationBuilder() - .AddJsonFile("appsettings.json") - .AddUserSecrets() - .Build(); + HostApplicationBuilder builder = Host.CreateApplicationBuilder(args); - IServiceCollection services = new ServiceCollection(); + builder.Services.AddDbContextFactory(options => { + options.UseNpgsql(builder.Configuration.GetConnectionString("EventsPostgres")); + }); + builder.Services.AddDbContextFactory(options => + { + options.UseSqlServer(builder.Configuration.GetConnectionString("EventsMssql")); + }); + + builder.Services.AddTransient(); - var provider = services.AddLogging(configure => { - configure.AddConfiguration(configuration.GetSection("Logging")); - configure.AddConsole(); - }) - .AddDbContext(options => { - options.UseSqlServer(configuration.GetConnectionString("EventsMssql")); - }, contextLifetime: ServiceLifetime.Transient) - .AddDbContext(options => { - options.UseNpgsql(configuration.GetConnectionString("EventsPostgres")); - }, contextLifetime: ServiceLifetime.Transient) - .BuildServiceProvider(); - return provider; + return builder.Build(); } -} +} \ No newline at end of file diff --git a/DataAccess/EF_Demo/Demo.cs b/DataAccess/EF_Demo/Demo.cs index d0555e6..68780bc 100644 --- a/DataAccess/EF_Demo/Demo.cs +++ b/DataAccess/EF_Demo/Demo.cs @@ -1,29 +1,28 @@ -#if POSTGRES +#if POSTGRES using EF_Demo.Data.Postgres; #else using EF_Demo.Data.MSSQL; #endif using EF_Demo.Models; -using Microsoft.Extensions.DependencyInjection; +using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; namespace EF_Demo; -internal class Demo +internal class Demo(IDbContextFactory contextFactory, ILogger logger) { - internal static int? AddEvent(IServiceProvider serviceProvider, string eventName, DateOnly eventDate) + internal int? AddEvent(string eventName, DateOnly eventDate) { - ILogger logger = serviceProvider.GetRequiredService>(); try { - using var ctx = serviceProvider.GetRequiredService(); + using var ctx = contextFactory.CreateDbContext(); Event @event = new() { Name = eventName, EventDate = eventDate }; - ctx.Add(@event); //or ctx.Events.Add(@event) or ctx.Set().Add(@event); + ctx.Add(@event); ctx.SaveChanges(); logger.LogInformation($"Event {eventName} successfully added with id {@event.Id}"); return @event.Id; @@ -35,16 +34,15 @@ internal class Demo } } - internal static void DeleteEvent(IServiceProvider serviceProvider, int eventId) + internal void DeleteEvent(int eventId) { - ILogger logger = serviceProvider.GetRequiredService>(); try { - using var ctx = serviceProvider.GetRequiredService(); + using var ctx = contextFactory.CreateDbContext(); Event? @event = ctx.Events.Find(eventId); if (@event != null) { - ctx.Remove(@event); //or ctx.Entry(product).State = EntityState.Deleted; + ctx.Remove(@event); ctx.SaveChanges(); logger.LogInformation($"Event {@event.Name} deleted"); } @@ -59,12 +57,11 @@ internal class Demo } } - internal static void PostponeEvent(IServiceProvider serviceProvider, int eventId, int days) + internal void PostponeEvent(int eventId, int days) { - ILogger logger = serviceProvider.GetRequiredService>(); try { - using var ctx = serviceProvider.GetRequiredService(); + using var ctx = contextFactory.CreateDbContext(); Event? @event = ctx.Events.Find(eventId); if (@event != null) { @@ -74,12 +71,12 @@ internal class Demo } else { - logger?.LogWarning($"Event #{eventId} does not exists"); + logger.LogWarning($"Event #{eventId} does not exists"); } } catch (Exception exc) { - logger?.LogError($"Error trying to change evenbt #{eventId}: {exc.CompleteExceptionMessage()}"); + logger.LogError($"Error trying to change evenbt #{eventId}: {exc.CompleteExceptionMessage()}"); } } @@ -87,12 +84,12 @@ internal class Demo /// Print all people born in the provided year, ordered by country, and then by transliterated last name, and first name /// query is projected to an anonymous class /// - internal static void PrintPeople(IServiceProvider serviceProvider, int year) + internal void PrintPeople(int year) { - using var ctx = serviceProvider.GetRequiredService(); + using var ctx = contextFactory.CreateDbContext(); var query = ctx.People .Where(p => p.BirthDate.Year == year) - .OrderBy(p => p.CountryCodeNavigation.Name) + .OrderBy(p => p.CountryCodeNavigation.Name) .ThenBy(p => p.LastNameTranscription) .ThenBy(p => p.FirstNameTranscription) .Select(p => new diff --git a/DataAccess/EF_Demo/EF_Demo.csproj b/DataAccess/EF_Demo/EF_Demo.csproj index aa7c91c..706ec77 100644 --- a/DataAccess/EF_Demo/EF_Demo.csproj +++ b/DataAccess/EF_Demo/EF_Demo.csproj @@ -12,7 +12,7 @@ - $(DefineConstants);POSTGRES + $(DefineConstants);MSSQL @@ -21,7 +21,7 @@ runtime; build; native; contentfiles; analyzers; buildtransitive - + diff --git a/DataAccess/EF_Demo/Program.cs b/DataAccess/EF_Demo/Program.cs index 11fe042..954b1ef 100644 --- a/DataAccess/EF_Demo/Program.cs +++ b/DataAccess/EF_Demo/Program.cs @@ -1,21 +1,22 @@ -using EF_Demo; +using EF_Demo; using Microsoft.Extensions.DependencyInjection; Console.OutputEncoding = System.Text.Encoding.UTF8; -using ServiceProvider serviceProvider = DISetup.BuildDI(); +using var host = DISetup.BuildHost(args); +Demo demo = host.Services.GetRequiredService(); -Demo.PrintPeople(serviceProvider, 1976); +demo.PrintPeople(1976); Util.EnterToContinue(); -int? eventId = Demo.AddEvent(serviceProvider, "Spring festival", new DateOnly(2026, 4, 30)); +int? eventId = demo.AddEvent("Spring festival", new DateOnly(2026, 4, 30)); Util.EnterToContinue(); if (eventId.HasValue) { - Demo.PostponeEvent(serviceProvider, eventId.Value, days: 5); + demo.PostponeEvent(eventId.Value, days: 5); Util.EnterToContinue(); - Demo.DeleteEvent(serviceProvider, eventId.Value); + demo.DeleteEvent(eventId.Value); Util.EnterToContinue(clearConsole: false); -} \ No newline at end of file +} diff --git a/DataAccess/EF_Demo/Properties/launchSettings.json b/DataAccess/EF_Demo/Properties/launchSettings.json new file mode 100644 index 0000000..f824762 --- /dev/null +++ b/DataAccess/EF_Demo/Properties/launchSettings.json @@ -0,0 +1,10 @@ +{ + "profiles": { + "DataGenerator": { + "commandName": "Project", + "environmentVariables": { + "DOTNET_ENVIRONMENT": "Development" + } + } + } +} diff --git a/DataAccess/EF_Demo/appsettings.json b/DataAccess/EF_Demo/appsettings.json index 8b5d9c0..c3ff50c 100644 --- a/DataAccess/EF_Demo/appsettings.json +++ b/DataAccess/EF_Demo/appsettings.json @@ -10,7 +10,7 @@ "Microsoft": "Error", "Microsoft.EntityFrameworkCore.Database.Command": "Information", "EF_Demo.Demo": "Information" - } + } } }