Skip to content

Commit 7060375

Browse files
committed
Migrate Autofac DI to Vanilla DI in the sample project (ardalis#723)
1 parent ff3fc53 commit 7060375

File tree

5 files changed

+132
-198
lines changed

5 files changed

+132
-198
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
using Microsoft.Extensions.DependencyInjection;
2+
using Microsoft.Extensions.Logging;
3+
using NimblePros.SampleToDo.Core.Interfaces;
4+
using NimblePros.SampleToDo.Core.Services;
5+
6+
namespace NimblePros.SampleToDo.Core;
7+
8+
public static class CoreServiceExtensions
9+
{
10+
public static IServiceCollection AddCoreServices(this IServiceCollection services, ILogger logger)
11+
{
12+
services.AddScoped<IToDoItemSearchService, ToDoItemSearchService>();
13+
services.AddScoped<IDeleteContributorService, DeleteContributorService>();
14+
15+
logger.LogInformation("{Project} services registered", "Core");
16+
17+
return services;
18+
}
19+
}

sample/src/NimblePros.SampleToDo.Core/DefaultCoreModule.cs

-20
This file was deleted.

sample/src/NimblePros.SampleToDo.Infrastructure/AutofacInfrastructureModule.cs

-153
This file was deleted.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
using Ardalis.SharedKernel;
2+
using Microsoft.Extensions.DependencyInjection;
3+
using Microsoft.Extensions.Logging;
4+
using NimblePros.SampleToDo.Core.Interfaces;
5+
using NimblePros.SampleToDo.Infrastructure.Data;
6+
using NimblePros.SampleToDo.Infrastructure.Data.Queries;
7+
using NimblePros.SampleToDo.Infrastructure.Email;
8+
using NimblePros.SampleToDo.UseCases.Contributors.List;
9+
using NimblePros.SampleToDo.UseCases.Projects.ListIncompleteItems;
10+
using NimblePros.SampleToDo.UseCases.Projects.ListShallow;
11+
12+
namespace NimblePros.SampleToDo.Infrastructure;
13+
14+
public static class InfrastructureServiceExtensions
15+
{
16+
public static IServiceCollection AddInfrastructureServices(
17+
this IServiceCollection services,
18+
ILogger logger,
19+
bool isDevelopment)
20+
{
21+
if (isDevelopment)
22+
{
23+
RegisterDevelopmentOnlyDependencies(services);
24+
}
25+
else
26+
{
27+
RegisterProductionOnlyDependencies(services);
28+
}
29+
30+
RegisterEF(services);
31+
32+
logger.LogInformation("{Project} services registered", "Infrastructure");
33+
34+
return services;
35+
}
36+
37+
private static void RegisterDevelopmentOnlyDependencies(IServiceCollection services)
38+
{
39+
services.AddScoped<IEmailSender, SmtpEmailSender>();
40+
services.AddScoped<IListContributorsQueryService, FakeListContributorsQueryService>();
41+
services.AddScoped<IListIncompleteItemsQueryService, FakeListIncompleteItemsQueryService>();
42+
services.AddScoped<IListProjectsShallowQueryService, FakeListProjectsShallowQueryService>();
43+
}
44+
45+
private static void RegisterProductionOnlyDependencies(IServiceCollection services)
46+
{
47+
services.AddScoped<IEmailSender, SmtpEmailSender>();
48+
services.AddScoped<IListContributorsQueryService, ListContributorsQueryService>();
49+
services.AddScoped<IListIncompleteItemsQueryService, ListIncompleteItemsQueryService>();
50+
services.AddScoped<IListProjectsShallowQueryService, ListProjectsShallowQueryService>();
51+
}
52+
53+
private static void RegisterEF(IServiceCollection services)
54+
{
55+
services.AddScoped(typeof(IRepository<>), typeof(EfRepository<>));
56+
services.AddScoped(typeof(IReadRepository<>), typeof(EfRepository<>));
57+
}
58+
}

sample/src/NimblePros.SampleToDo.Web/Program.cs

+55-25
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,32 @@
1-
using Ardalis.ListStartupServices;
2-
using Autofac;
3-
using Autofac.Extensions.DependencyInjection;
1+
using System.Reflection;
2+
using Ardalis.ListStartupServices;
3+
using Ardalis.SharedKernel;
44
using NimblePros.SampleToDo.Core;
55
using NimblePros.SampleToDo.Infrastructure;
66
using NimblePros.SampleToDo.Infrastructure.Data;
77
using NimblePros.SampleToDo.Web;
88
using FastEndpoints;
99
using FastEndpoints.Swagger;
1010
using FastEndpoints.ApiExplorer;
11+
using MediatR;
1112
using Serilog;
1213
using Microsoft.EntityFrameworkCore;
14+
using NimblePros.SampleToDo.Core.ProjectAggregate;
15+
using NimblePros.SampleToDo.UseCases.Contributors.Create;
16+
using Serilog.Extensions.Logging;
1317

14-
var builder = WebApplication.CreateBuilder(args);
18+
var logger = Log.Logger = new LoggerConfiguration()
19+
.Enrich.FromLogContext()
20+
.WriteTo.Console()
21+
.CreateLogger();
22+
23+
logger.Information("Starting web host");
1524

16-
builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
25+
var builder = WebApplication.CreateBuilder(args);
1726

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

2031
builder.Services.Configure<CookiePolicyOptions>(options =>
2132
{
@@ -43,6 +54,11 @@
4354
// c.OperationFilter<FastEndpointsOperationFilter>();
4455
//});
4556

57+
builder.Services.AddCoreServices(microsoftLogger);
58+
builder.Services.AddInfrastructureServices(microsoftLogger, builder.Environment.IsDevelopment());
59+
60+
ConfigureMediatR();
61+
4662
// add list services for diagnostic purposes - see https://github.com/ardalis/AspNetCoreStartupServices
4763
builder.Services.Configure<ServiceConfig>(config =>
4864
{
@@ -53,12 +69,6 @@
5369
});
5470

5571

56-
builder.Host.ConfigureContainer<ContainerBuilder>(containerBuilder =>
57-
{
58-
containerBuilder.RegisterModule(new DefaultCoreModule());
59-
containerBuilder.RegisterModule(new AutofacInfrastructureModule(builder.Environment.IsDevelopment()));
60-
});
61-
6272
var app = builder.Build();
6373

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

8292
// Seed Database
83-
using (var scope = app.Services.CreateScope())
84-
{
85-
var services = scope.ServiceProvider;
93+
SeedDatabase(app);
8694

87-
try
95+
app.Run();
96+
97+
98+
void ConfigureMediatR()
99+
{
100+
var mediatRAssemblies = new[]
88101
{
89-
var context = services.GetRequiredService<AppDbContext>();
90-
// context.Database.Migrate();
91-
context.Database.EnsureCreated();
92-
SeedData.Initialize(services);
93-
}
94-
catch (Exception ex)
102+
Assembly.GetAssembly(typeof(Project)), // Core
103+
Assembly.GetAssembly(typeof(CreateContributorCommand)), // UseCases
104+
Assembly.GetAssembly(typeof(InfrastructureServiceExtensions)) // Infrastructure
105+
};
106+
107+
builder.Services.AddMediatR(cfg => cfg.RegisterServicesFromAssemblies(mediatRAssemblies!));
108+
builder.Services.AddScoped(typeof(IPipelineBehavior<,>), typeof(LoggingBehavior<,>));
109+
builder.Services.AddScoped<IDomainEventDispatcher, MediatRDomainEventDispatcher>();
110+
}
111+
112+
void SeedDatabase(WebApplication app)
113+
{
114+
using (var scope = app.Services.CreateScope())
95115
{
96-
var logger = services.GetRequiredService<ILogger<Program>>();
97-
logger.LogError(ex, "An error occurred seeding the DB. {exceptionMessage}", ex.Message);
116+
var services = scope.ServiceProvider;
117+
118+
try
119+
{
120+
var context = services.GetRequiredService<AppDbContext>();
121+
// context.Database.Migrate();
122+
context.Database.EnsureCreated();
123+
SeedData.Initialize(services);
124+
}
125+
catch (Exception ex)
126+
{
127+
var logger = services.GetRequiredService<ILogger<Program>>();
128+
logger.LogError(ex, "An error occurred seeding the DB. {exceptionMessage}", ex.Message);
129+
}
98130
}
99131
}
100132

101-
app.Run();
102-
103133
// Make the implicit Program.cs class public, so integration tests can reference the correct assembly for host building
104134
public partial class Program
105135
{

0 commit comments

Comments
 (0)