.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.
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
7. 7
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
8. 8
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