DI Setup using HostApplicationBuilder
This commit is contained in:
@@ -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<Program>()
|
||||
.Build();
|
||||
HostApplicationBuilder builder = Host.CreateApplicationBuilder(args);
|
||||
|
||||
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 => {
|
||||
configure.AddConfiguration(configuration.GetSection("Logging"));
|
||||
configure.AddConsole();
|
||||
})
|
||||
.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;
|
||||
builder.Services.AddTransient<Demo>();
|
||||
|
||||
return builder.Build();
|
||||
}
|
||||
}
|
||||
@@ -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<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
|
||||
{
|
||||
using var ctx = serviceProvider.GetRequiredService<EventsContext>();
|
||||
using var ctx = contextFactory.CreateDbContext();
|
||||
Event @event = new()
|
||||
{
|
||||
Name = eventName,
|
||||
EventDate = eventDate
|
||||
};
|
||||
ctx.Add(@event); //or ctx.Events.Add(@event) or ctx.Set<Event>().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<ILogger<Demo>>();
|
||||
try
|
||||
{
|
||||
using var ctx = serviceProvider.GetRequiredService<EventsContext>();
|
||||
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<ILogger<Demo>>();
|
||||
try
|
||||
{
|
||||
using var ctx = serviceProvider.GetRequiredService<EventsContext>();
|
||||
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,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
|
||||
/// query is projected to an anonymous class
|
||||
/// </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
|
||||
.Where(p => p.BirthDate.Year == year)
|
||||
.OrderBy(p => p.CountryCodeNavigation.Name)
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
</PropertyGroup>
|
||||
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
|
||||
<DefineConstants>$(DefineConstants);POSTGRES</DefineConstants>
|
||||
<DefineConstants>$(DefineConstants);MSSQL</DefineConstants>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
@@ -21,7 +21,7 @@
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
<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="Npgsql.EntityFrameworkCore.PostgreSQL" Version="10.0.1" />
|
||||
</ItemGroup>
|
||||
|
||||
@@ -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>();
|
||||
|
||||
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);
|
||||
}
|
||||
10
DataAccess/EF_Demo/Properties/launchSettings.json
Normal file
10
DataAccess/EF_Demo/Properties/launchSettings.json
Normal file
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"profiles": {
|
||||
"DataGenerator": {
|
||||
"commandName": "Project",
|
||||
"environmentVariables": {
|
||||
"DOTNET_ENVIRONMENT": "Development"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user