DI Setup using HostApplicationBuilder

This commit is contained in:
Boris Milašinović
2026-04-20 20:28:54 +02:00
parent b47ad41296
commit be194688bd
6 changed files with 53 additions and 50 deletions

View File

@@ -1,32 +1,27 @@
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
namespace EF_Demo; namespace EF_Demo;
internal class DISetup internal static class DISetup
{ {
public static ServiceProvider BuildDI() public static IHost BuildHost(string[] args)
{ {
var configuration = new ConfigurationBuilder() HostApplicationBuilder builder = Host.CreateApplicationBuilder(args);
.AddJsonFile("appsettings.json")
.AddUserSecrets<Program>()
.Build();
IServiceCollection services = new ServiceCollection(); builder.Services.AddDbContextFactory<Data.Postgres.EventsContext>(options => {
options.UseNpgsql(builder.Configuration.GetConnectionString("EventsPostgres"));
});
builder.Services.AddDbContextFactory<Data.MSSQL.EventsContext>(options =>
{
options.UseSqlServer(builder.Configuration.GetConnectionString("EventsMssql"));
});
var provider = services.AddLogging(configure => { builder.Services.AddTransient<Demo>();
configure.AddConfiguration(configuration.GetSection("Logging"));
configure.AddConsole(); return builder.Build();
})
.AddDbContext<Data.MSSQL.EventsContext>(options => {
options.UseSqlServer(configuration.GetConnectionString("EventsMssql"));
}, contextLifetime: ServiceLifetime.Transient)
.AddDbContext<Data.Postgres.EventsContext>(options => {
options.UseNpgsql(configuration.GetConnectionString("EventsPostgres"));
}, contextLifetime: ServiceLifetime.Transient)
.BuildServiceProvider();
return provider;
} }
} }

View File

@@ -1,29 +1,28 @@
#if POSTGRES #if POSTGRES
using EF_Demo.Data.Postgres; using EF_Demo.Data.Postgres;
#else #else
using EF_Demo.Data.MSSQL; using EF_Demo.Data.MSSQL;
#endif #endif
using EF_Demo.Models; using EF_Demo.Models;
using Microsoft.Extensions.DependencyInjection; using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
namespace EF_Demo; namespace EF_Demo;
internal class Demo internal class Demo(IDbContextFactory<EventsContext> contextFactory, ILogger<Demo> logger)
{ {
internal static int? AddEvent(IServiceProvider serviceProvider, string eventName, DateOnly eventDate) internal int? AddEvent(string eventName, DateOnly eventDate)
{ {
ILogger logger = serviceProvider.GetRequiredService<ILogger<Demo>>();
try try
{ {
using var ctx = serviceProvider.GetRequiredService<EventsContext>(); using var ctx = contextFactory.CreateDbContext();
Event @event = new() Event @event = new()
{ {
Name = eventName, Name = eventName,
EventDate = eventDate EventDate = eventDate
}; };
ctx.Add(@event); //or ctx.Events.Add(@event) or ctx.Set<Event>().Add(@event); ctx.Add(@event);
ctx.SaveChanges(); ctx.SaveChanges();
logger.LogInformation($"Event {eventName} successfully added with id {@event.Id}"); logger.LogInformation($"Event {eventName} successfully added with id {@event.Id}");
return @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<ILogger<Demo>>();
try try
{ {
using var ctx = serviceProvider.GetRequiredService<EventsContext>(); using var ctx = contextFactory.CreateDbContext();
Event? @event = ctx.Events.Find(eventId); Event? @event = ctx.Events.Find(eventId);
if (@event != null) if (@event != null)
{ {
ctx.Remove(@event); //or ctx.Entry(product).State = EntityState.Deleted; ctx.Remove(@event);
ctx.SaveChanges(); ctx.SaveChanges();
logger.LogInformation($"Event {@event.Name} deleted"); 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<ILogger<Demo>>();
try try
{ {
using var ctx = serviceProvider.GetRequiredService<EventsContext>(); using var ctx = contextFactory.CreateDbContext();
Event? @event = ctx.Events.Find(eventId); Event? @event = ctx.Events.Find(eventId);
if (@event != null) if (@event != null)
{ {
@@ -74,12 +71,12 @@ internal class Demo
} }
else else
{ {
logger?.LogWarning($"Event #{eventId} does not exists"); logger.LogWarning($"Event #{eventId} does not exists");
} }
} }
catch (Exception exc) catch (Exception exc)
{ {
logger?.LogError($"Error trying to change evenbt #{eventId}: {exc.CompleteExceptionMessage()}"); logger.LogError($"Error trying to change evenbt #{eventId}: {exc.CompleteExceptionMessage()}");
} }
} }
@@ -87,9 +84,9 @@ internal class Demo
/// Print all people born in the provided year, ordered by country, and then by transliterated last name, and first name /// 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 /// query is projected to an anonymous class
/// </summary> /// </summary>
internal static void PrintPeople(IServiceProvider serviceProvider, int year) internal void PrintPeople(int year)
{ {
using var ctx = serviceProvider.GetRequiredService<EventsContext>(); using var ctx = contextFactory.CreateDbContext();
var query = ctx.People var query = ctx.People
.Where(p => p.BirthDate.Year == year) .Where(p => p.BirthDate.Year == year)
.OrderBy(p => p.CountryCodeNavigation.Name) .OrderBy(p => p.CountryCodeNavigation.Name)

View File

@@ -12,7 +12,7 @@
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'"> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<DefineConstants>$(DefineConstants);POSTGRES</DefineConstants> <DefineConstants>$(DefineConstants);MSSQL</DefineConstants>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
@@ -21,7 +21,7 @@
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference> </PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="10.0.6" /> <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="10.0.6" />
<PackageReference Include="Microsoft.Extensions.Configuration.UserSecrets" Version="10.0.6" /> <PackageReference Include="Microsoft.Extensions.Hosting" Version="10.0.6" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="10.0.6" /> <PackageReference Include="Microsoft.Extensions.Logging.Console" Version="10.0.6" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="10.0.1" /> <PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="10.0.1" />
</ItemGroup> </ItemGroup>

View File

@@ -1,21 +1,22 @@
using EF_Demo; using EF_Demo;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
Console.OutputEncoding = System.Text.Encoding.UTF8; Console.OutputEncoding = System.Text.Encoding.UTF8;
using ServiceProvider serviceProvider = DISetup.BuildDI(); using var host = DISetup.BuildHost(args);
Demo demo = host.Services.GetRequiredService<Demo>();
Demo.PrintPeople(serviceProvider, 1976); demo.PrintPeople(1976);
Util.EnterToContinue(); 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(); Util.EnterToContinue();
if (eventId.HasValue) if (eventId.HasValue)
{ {
Demo.PostponeEvent(serviceProvider, eventId.Value, days: 5); demo.PostponeEvent(eventId.Value, days: 5);
Util.EnterToContinue(); Util.EnterToContinue();
Demo.DeleteEvent(serviceProvider, eventId.Value); demo.DeleteEvent(eventId.Value);
Util.EnterToContinue(clearConsole: false); Util.EnterToContinue(clearConsole: false);
} }

View File

@@ -0,0 +1,10 @@
{
"profiles": {
"DataGenerator": {
"commandName": "Project",
"environmentVariables": {
"DOTNET_ENVIRONMENT": "Development"
}
}
}
}