Verifying your DI Container #57
Replies: 2 comments 5 replies
-
|
Hey Steven,
builder.Host.UseDefaultServiceProvider(
(context, options) =>
{
var isDevMode =
context.HostingEnvironment.IsDevelopment()
|| context.HostingEnvironment.IsEnvironment("test")
|| context.HostingEnvironment.IsStaging();
// CreateDefaultBuilder and WebApplicationBuilder in minimal apis sets `ServiceProviderOptions.ValidateScopes` and `ServiceProviderOptions.ValidateOnBuild` to true if the app's environment is Development.
options.ValidateScopes = isDevMode;
options.ValidateOnBuild = isDevMode;
}
public static void ValidateDependencies(
this IServiceProvider rootServiceProvider,
IServiceCollection services,
params Assembly[] assembliesToScan
)
{
var scanAssemblies = assembliesToScan.Any() ? assembliesToScan : new[] { Assembly.GetExecutingAssembly(), };
var exceptions = new List<string>();
// for resolving scoped based dependencies without errors
using var scope = rootServiceProvider.CreateScope();
var sp = scope.ServiceProvider;
foreach (var serviceDescriptor in services)
{
try
{
var serviceType = serviceDescriptor.ServiceType;
if (scanAssemblies.Contains(serviceType.Assembly))
sp.GetRequiredService(serviceType);
}
catch (Exception e)
{
exceptions.Add($"Unable to resolve '{serviceDescriptor.ServiceType.FullName}', detail: {e.Message}");
}
}
if (exceptions.Any())
{
throw new Exception(string.Join("\n", exceptions));
}
}
|
Beta Was this translation helpful? Give feedback.
5 replies
-
|
Awesome blog, thanks! |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Verifying your DI Container
Microsoft's integrated dependency injection (short DI) container is very powerful, but there are also certain pitfalls. In this article, I will show you what some of the pitfalls are and how you can verify them.
https://steven-giesel.com/blogPost/ce948083-974a-4c16-877f-246b8909fa6d
Beta Was this translation helpful? Give feedback.
All reactions