Tutorial by Examples

The preferred way of describing dependencies is by using constructor injection which follows Explicit Dependencies Principle: ITestService.cs public interface ITestService { int GenerateRandom(); } TestService.cs public class TestService : ITestService { public int GenerateRando...
Builtin container comes with a set of builtin features : Lifetime control public void ConfigureServices(IServiceCollection services) { // ... services.AddTransient<ITestService, TestService>(); // or services.AddScoped<ITestService, TestSer...
Once registered a dependency can be retrieved by adding parameters on the Controller constructor. // ... using System; using Microsoft.Extensions.DependencyInjection; namespace Core.Controllers { public class HomeController : Controller { public HomeController(ITestServic...
A less known builtin feature is Controller Action injection using the FromServicesAttribute. [HttpGet] public async Task<IActionResult> GetAllAsync([FromServices]IProductService products) { return Ok(await products.GetAllAsync()); } An important note is that the [FromServices] c...
With ASP.NET Core the Microsoft team also introduced the Options pattern, which allows to have strong typed options and once configured the ability to inject the options into your services. First we start with a strong typed class, which will hold our configuration. public class MySettings { ...
Resolving scoped services during application startup can be difficult, because there is no request and hence no scoped service. Resolving a scoped service during application startup via app.ApplicationServices.GetService<AppDbContext>() can cause issues, because it will be created in the sc...
By default Controllers, ViewComponents and TagHelpers aren't registered and resolved via the dependency injection container. This results in the inability to do i.e. property injection when using a 3rd party Inversion of Control (IoC) container like AutoFac. In order to make ASP.NET Core MVC resolv...
This shows you how to use Microsoft.Extensions.DependencyInjection nuget package without the use of the WebHostBuilder from kestrel (e.g. when you want to build something else then a webApp): internal class Program { public static void Main(string[] args) { var services = new Se...
IServiceCollection To start building an IOC container with Microsoft's DI nuget package you start with creating an IServiceCollection. You can use the already provided Collection: ServiceCollection: var services = new ServiceCollection(); This IServiceCollection is nothing more than an implemen...

Page 1 of 1