ASP.NET Core offers a built in IOC container to manage your Dependency Injection. You may have seen this used in some of our previous tutorials.

It’s an extremely powerful tool when creating instances of objects such as your loggers and database connections inside of services and using them throughout your application. There is a lot of good documentation on this feature on the official Microsoft website. You can also subscribe to our videos and get access to tutorials on IOC and more.

What are IOC Containers?

IOC containers implement automatic Dependency Injection. You set the dependencies in the container and use instances of them throughout your application. This, of course, is a simplified example of this.

Registering Services

In order to use DI (Dependency Injection), it must be registered as a service.

public void ConfigureServices(IServiceCollection services)
        {
            // requires using Microsoft.Extensions.Options
            services.Configure<TodosDatabaseSettings>(
                Configuration.GetSection(nameof(TodosDatabaseSettings)));

            services.AddSingleton<ITodosDatabaseSettings>(sp =>
                sp.GetRequiredService<IOptions<TodosDatabaseSettings>>().Value);
            services.AddSingleton<TodosRepository>();
            services.AddControllers();
        }

Several Services are registered here such as our Repository for our DB, our Configuration of the DB and the registration of controllers.

Singleton Services

Singletons are one instance of a class to be used throughout the application. An example of this would be a logger.

Transient Services

Unlike Singletons, Transient services are created each time they are requested.

Scoped Services

Scoped Services are the different for each client request. The difference being with Scoped Services, the client is requesting them instead of the container.

Conclusion

Dependency Injection can be difficult to understand at first but with experience, it is easier to understand. You can check out some of the examples in our video tutorials here.

Codebrains Newsletter

Get weekly dev news and tutorials.

Powered by ConvertKit