Diese Präsentation wurde erfolgreich gemeldet.
Wir verwenden Ihre LinkedIn Profilangaben und Informationen zu Ihren Aktivitäten, um Anzeigen zu personalisieren und Ihnen relevantere Inhalte anzuzeigen. Sie können Ihre Anzeigeneinstellungen jederzeit ändern.

It depends: Loving .NET Core dependency injection or not

.NET Core comes with its own dependency injection system, that you probably know from ASP.NET Core. In this session we will have a detailed look at all of the specifics of Microsoft's default DI system for .NET Core applications. You will learn how to properly use the Inversion of Control features, such as registering services, scopes, lifetimes, and how to resolve instances.
Armed with this DI knowledge, we will revisit ASP.NET Core and investigate bootstrapping and typical scenarios for middleware, background processes and resolving objects from MVC and Razor.
At the end there will be a deep dive into topics with service descriptors, implementation factories, do's and don'ts and pitfalls to avoid memory leaks in your implementation.

  • Loggen Sie sich ein, um Kommentare anzuzeigen.

It depends: Loving .NET Core dependency injection or not

  1. 1. 1. Unit testing 2. SOLID: Dependency Inversion Principle 3. Loose coupling 4. Clean architecture 5. .NET Core is using it Related Domain Logic Presentation From Jason Taylor: Clean Architecture with ASP.NET Core 2.2
  2. 2. Container HomeController FloppyDiskRepository IRepository ILogger ConsoleLogger
  3. 3. Possible ways to map Try Add<ServiceType ImplementationType> Builder pattern Add TryAdd ServiceType ImplementationType
  4. 4. Demo: ASP.NET Core DI Quick look at how you were using dependency injection all along
  5. 5. Register • How • Add… and TryAdd… of type mappings • Add… extension methods • Where • Application root • Startup class (ASP.NET) Resolve • Implicit • Constructor injection • ASP.NET Core specifics • Explicit • GetService<T> • GetRequiredService<T> • Also for enumerables Release • Automatic • Resolved instances and dependencies • Scopes • End of scope • Might need to create child scopes IServiceCollection IServiceProvider IDisposable 1 2 3
  6. 6. Singleton • Easy way to implement singleton pattern • One instance per DI container • Beware of concurrency and threading issues Scoped • Duration of scope • ASP.NET uses web request as scope • Useful for UnitOfWork objects, e.g. DbContext • See also ServiceScopeFactory Transient • Single use • Most common and safest
  7. 7. Typical startup in ASP.NET Core public class Startup { public Startup(IConfiguration configuration, IHostEnvironment env) public void ConfigureServices(IServiceCollection services) public void Configure(IApplicationBuilder app, IWebHostEnvironment env, …) } builder.UseStartup<Startup>(); 1 2 3
  8. 8. Many ways to inject a service instance IServiceProvider Pro tip ActivatorUtilities IServiceProvider Register using Configure(Services) injection in Startup class Constructor injection [FromServices] attribute @inject IApplicationBuilder. ApplicationServices HttpContext. RequestServices Middleware Constructor or Invoke method
  9. 9. Demo: Resolving services in ASP.NET Core Controllerconstructors @inject FromServicesAttribute Application-andRequestServices
  10. 10. Hosting outside and without ASP.NET Core IHostedService BackgroundService Uses new Host, and IHostBuilder for hosting WebHostBuilder HostBuilder Configure Startup Microsoft.Extensions.Hosting Microsoft.Extensions.DependencyInjection
  11. 11. Resolved instances are released at end of scope IDisposable Dispose Create your own scopes with ServiceScopeFactory Especially important for hosted services AddHostedService<T> using (var scope = serviceScopeFactory.CreateScope()) { ISomeRepository scoped = scope.ServiceProvider.GetRequiredService<ISomeRepository>(); await DoMyWork(scoped); }
  12. 12. Check lifetime restrictions Prevent memory leaks and unexpected behavior Host.CreateDefaultBuilder(args) .UseDefaultServiceProvider((context, options) => { options.ValidateScopes = context.HostingEnvironment.IsDevelopment(); options.ValidateOnBuild = true; // .NET Core 3.0 })
  13. 13. Demo: Generic Host New .NET Core 3.0 hosting Scope validation Using scopes
  14. 14. Too much abstractions Conforming container Easy to use anti-patterns
  15. 15. Microsoft.Extension.DependencyInjection DefaultServiceProviderFactoryDuring configuring ServiceDescriptors IServiceProviderFactory<T> CreateServiceProvider CreateBuilder ContainerBuilder Build System.ComponentModel.IServiceProvider LightInjectServiceProviderFactory During runtime ServiceProvider GetService<T> LightInjectServiceProvider GetService<T> IServiceContainer Build IServiceProviderFactory<T> CreateServiceProvider CreateBuilder
  16. 16. Plug in your favorite DI Framework Option 1: While building host UseServiceProviderFactory ConfigureContainer Option 2: When configuring services ConfigureServices IServiceProvider Some alternative DI Frameworks Autofac Castle Windsor Lamar LightInject Ninject SimpleInjector Spring.NET Unity
  17. 17. Demo: Advanced DI Replacing DI container Custom DI containers
  18. 18. Different registrations for environments Configure{Environment}Services Configure{Environment} Startup{Environment} StartupProduction Requires different startup UseStartup<Startup> Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { var assembly = typeof(Startup).GetTypeInfo().Assembly; webBuilder.UseStartup(assemblyName.GetName().Name); });
  19. 19. Demo: Tips and tricks Convention based startup TestServer services override
  20. 20. Avoid use Service Locator pattern IServiceProvider IServiceScopeFactory.CreateScope Do not directly inject HttpContext IHttpContextAccessor accessor.HttpContext.RequestServices Avoid complex lifetime graphs
  21. 21. Dependency injection is integral part of .NET Core If you do not like it, replace it
  22. 22. Questions and Answers Demo code: https://github.com/alexthissen/DependencyInjection
  23. 23. Resources https://docs.microsoft.com/en-us/azure/architecture/patterns/health-endpoint-monitoring https://docs.microsoft.com/en-us/aspnet/core/host-and-deploy/health-checks https://github.com/aspnet/Diagnostics/tree/master/src https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-probes/ https://github.com/Xabaril/AspNetCore.Diagnostics.HealthChecks https://github.com/alexthissen/healthmonitoring

×