Skip to content

Commit

Permalink
Migrate Autofac DI to Vanilla DI in the sample project (ardalis#723)
Browse files Browse the repository at this point in the history
  • Loading branch information
teilus committed Apr 10, 2024
1 parent ff3fc53 commit 38f0258
Show file tree
Hide file tree
Showing 5 changed files with 132 additions and 198 deletions.
19 changes: 19 additions & 0 deletions sample/src/NimblePros.SampleToDo.Core/CoreServiceExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NimblePros.SampleToDo.Core.Interfaces;
using NimblePros.SampleToDo.Core.Services;

namespace NimblePros.SampleToDo.Core;

public static class CoreServiceExtensions
{
public static IServiceCollection AddCoreServices(this IServiceCollection services, ILogger logger)
{
services.AddScoped<IToDoItemSearchService, ToDoItemSearchService>();
services.AddScoped<IDeleteContributorService, DeleteContributorService>();

logger.LogInformation("{Project} services registered", "Core");

return services;
}
}
20 changes: 0 additions & 20 deletions sample/src/NimblePros.SampleToDo.Core/DefaultCoreModule.cs

This file was deleted.

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
using Ardalis.SharedKernel;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NimblePros.SampleToDo.Core.Interfaces;
using NimblePros.SampleToDo.Infrastructure.Data;
using NimblePros.SampleToDo.Infrastructure.Data.Queries;
using NimblePros.SampleToDo.Infrastructure.Email;
using NimblePros.SampleToDo.UseCases.Contributors.List;
using NimblePros.SampleToDo.UseCases.Projects.ListIncompleteItems;
using NimblePros.SampleToDo.UseCases.Projects.ListShallow;

namespace NimblePros.SampleToDo.Infrastructure;

public static class InfrastructureServiceExtensions
{
public static IServiceCollection AddInfrastructureServices(
this IServiceCollection services,
ILogger logger,
bool isDevelopment)
{
if (isDevelopment)
{
RegisterDevelopmentOnlyDependencies(services);
}
else
{
RegisterProductionOnlyDependencies(services);
}

RegisterEF(services);

logger.LogInformation("{Project} services registered", "Infrastructure");

return services;
}

private static void RegisterDevelopmentOnlyDependencies(IServiceCollection services)
{
services.AddScoped<IEmailSender, SmtpEmailSender>();
services.AddScoped<IListContributorsQueryService, FakeListContributorsQueryService>();
services.AddScoped<IListIncompleteItemsQueryService, FakeListIncompleteItemsQueryService>();
services.AddScoped<IListProjectsShallowQueryService, FakeListProjectsShallowQueryService>();
}

private static void RegisterProductionOnlyDependencies(IServiceCollection services)
{
services.AddScoped<IEmailSender, SmtpEmailSender>();
services.AddScoped<IListContributorsQueryService, ListContributorsQueryService>();
services.AddScoped<IListIncompleteItemsQueryService, ListIncompleteItemsQueryService>();
services.AddScoped<IListProjectsShallowQueryService, ListProjectsShallowQueryService>();
}

private static void RegisterEF(IServiceCollection services)
{
services.AddScoped(typeof(IRepository<>), typeof(EfRepository<>));
services.AddScoped(typeof(IReadRepository<>), typeof(EfRepository<>));
}
}
80 changes: 55 additions & 25 deletions sample/src/NimblePros.SampleToDo.Web/Program.cs
Original file line number Diff line number Diff line change
@@ -1,21 +1,32 @@
using Ardalis.ListStartupServices;
using Autofac;
using Autofac.Extensions.DependencyInjection;
using System.Reflection;
using Ardalis.ListStartupServices;
using Ardalis.SharedKernel;
using NimblePros.SampleToDo.Core;
using NimblePros.SampleToDo.Infrastructure;
using NimblePros.SampleToDo.Infrastructure.Data;
using NimblePros.SampleToDo.Web;
using FastEndpoints;
using FastEndpoints.Swagger;
using FastEndpoints.ApiExplorer;
using MediatR;
using Serilog;
using Microsoft.EntityFrameworkCore;
using NimblePros.SampleToDo.Core.ProjectAggregate;
using NimblePros.SampleToDo.UseCases.Contributors.Create;
using Serilog.Extensions.Logging;

var builder = WebApplication.CreateBuilder(args);
var logger = Log.Logger = new LoggerConfiguration()
.Enrich.FromLogContext()
.WriteTo.Console()
.CreateLogger();

logger.Information("Starting web host");

builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
var builder = WebApplication.CreateBuilder(args);

builder.Host.UseSerilog((_, config) => config.ReadFrom.Configuration(builder.Configuration));
var microsoftLogger = new SerilogLoggerFactory(logger)
.CreateLogger<Program>();

builder.Services.Configure<CookiePolicyOptions>(options =>
{
Expand Down Expand Up @@ -43,6 +54,11 @@
// c.OperationFilter<FastEndpointsOperationFilter>();
//});

builder.Services.AddCoreServices(microsoftLogger);
builder.Services.AddInfrastructureServices(microsoftLogger, builder.Environment.IsDevelopment());

ConfigureMediatR();

// add list services for diagnostic purposes - see https://github.com/ardalis/AspNetCoreStartupServices
builder.Services.Configure<ServiceConfig>(config =>
{
Expand All @@ -53,12 +69,6 @@
});


builder.Host.ConfigureContainer<ContainerBuilder>(containerBuilder =>
{
containerBuilder.RegisterModule(new DefaultCoreModule());
containerBuilder.RegisterModule(new AutofacInfrastructureModule(builder.Environment.IsDevelopment()));
});

var app = builder.Build();

if (app.Environment.IsDevelopment())
Expand All @@ -80,26 +90,46 @@
//app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1"));

// Seed Database
using (var scope = app.Services.CreateScope())
{
var services = scope.ServiceProvider;
SeedDatabase(app);

try
app.Run();


void ConfigureMediatR()
{
var mediatRAssemblies = new[]
{
var context = services.GetRequiredService<AppDbContext>();
// context.Database.Migrate();
context.Database.EnsureCreated();
SeedData.Initialize(services);
}
catch (Exception ex)
Assembly.GetAssembly(typeof(Project)), // Core
Assembly.GetAssembly(typeof(CreateContributorCommand)), // UseCases
Assembly.GetAssembly(typeof(InfrastructureServiceExtensions)) // Infrastructure
};

builder.Services.AddMediatR(cfg => cfg.RegisterServicesFromAssemblies(mediatRAssemblies!));
builder.Services.AddScoped(typeof(IPipelineBehavior<,>), typeof(LoggingBehavior<,>));
builder.Services.AddScoped<IDomainEventDispatcher, MediatRDomainEventDispatcher>();
}

void SeedDatabase(WebApplication app)
{
using (var scope = app.Services.CreateScope())
{
var logger = services.GetRequiredService<ILogger<Program>>();
logger.LogError(ex, "An error occurred seeding the DB. {exceptionMessage}", ex.Message);
var services = scope.ServiceProvider;

try
{
var context = services.GetRequiredService<AppDbContext>();
// context.Database.Migrate();
context.Database.EnsureCreated();
SeedData.Initialize(services);
}
catch (Exception ex)
{
var logger = services.GetRequiredService<ILogger<Program>>();
logger.LogError(ex, "An error occurred seeding the DB. {exceptionMessage}", ex.Message);
}
}
}

app.Run();

// Make the implicit Program.cs class public, so integration tests can reference the correct assembly for host building
public partial class Program
{
Expand Down

0 comments on commit 38f0258

Please sign in to comment.