New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Migrate Autofac DI -> Native DI in Asp.Net Core #701
Conversation
sauravbhattacharya001
commented
Mar 2, 2024
- Remove the Autofac ContainerBuilder configuration
- Set up DI in the Program.cs top-level file
- Clean up Autofac in packages, documentation, and other helper classes.
Co-authored-by: cameronslatton@gmail.com Co-authored-by: marcotello5@outlook.com Co-authored-by: spitale@hotmail.it
Fixes #694 |
Co-authored-by: Kyle McMaster <KyleMcMaster@users.noreply.github.com>
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
My way is not the only way, our main goal is to keep the Program.cs file clean.
Parts that could grow should have their own section.
} | ||
} | ||
|
||
builder.Services.AddScoped(typeof(IRepository<>), typeof(EfRepository<>)); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
We should clean this up.
I wrote a blog post on this topic.
In Program.cs builder is in scope wherever you use it.
var mediatrOpenTypes = new[] | ||
{ | ||
containerBuilder.RegisterModule(new DefaultCoreModule()); | ||
containerBuilder.RegisterModule(new AutofacInfrastructureModule(builder.Environment.IsDevelopment())); | ||
}); | ||
typeof(IRequestHandler<,>), | ||
typeof(IRequestExceptionHandler<,,>), | ||
typeof(IRequestExceptionAction<,>), | ||
typeof(INotificationHandler<>), | ||
}; | ||
|
||
foreach (var assembly in assemblies) | ||
{ | ||
foreach (var openInterfaceType in mediatrOpenTypes) | ||
{ | ||
if (assembly != null) | ||
{ | ||
assembly.GetTypes() | ||
.Where(t => t.IsClass && !t.IsAbstract && t.GetInterfaces().Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == openInterfaceType)) | ||
.ToList() | ||
.ForEach(implementationType => | ||
{ | ||
var serviceType = implementationType.GetInterfaces().First(i => i.IsGenericType && i.GetGenericTypeDefinition() == openInterfaceType); | ||
builder.Services.AddScoped(serviceType, implementationType); | ||
}); | ||
} | ||
} | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Can this loop be removed in favor of using MediatR's own DI registration method?
builder.Services.AddMediatR(cfg => cfg.RegisterServicesFromAssemblies(assemblies));