Przejdź do głównej zawartości

Dependency Injection in .NET Core

Today I explain how Dependency Injection works in .NET Core and I describe 3 methods available in service provider.


Up to now if ASP.NET developers wanted to use dependency injection container they had to use Ninject, Autofac or another one.
To set these up we had to get NuGet package, install it and configure it in our config filels.

Good news - with ASP.NET Core new alternative comes. We don't need Ninject or Autofac anymore, because ASP.NET Core MVC has its own built-in dependency injection container.
All set up when new project is created. There is no need to install packages and modifying configuration files.

There are 3 methots that we can use to define dependencies in ASP.NET MVC: transient, singleton, scoper
Let's open Visual Studio and create new ASP.NET Core MVC application.

We'l focus on Startup.cs class where you can see ConfigureServices method.
If you want to instruct MVC to use specific class when controller asks for IEventRepository interface, you should put your code into this method.
Let's see how it can look like for 4 available options:


OPTION 1 - ADD TRANSIENT

This option is easy to understand. When you use AddTransient method, a new MongoEventRepository class will be instantiated every time when controller tries to use IEventRepository.
This is important to understand that MVC instantiates a new controller on each call. In practice it means that with each new HTTP request a new controller instance will be created and MongoEventRepository class will be created from scratch as a new instance.

OPTION 2 - ADD SINGLETON
Now let's change AddTransient to AddSingleton. Doing so we instruct MVC to create one single instance of MongoEventRepository class which will be shared by all the application components.
This means that for each HTTP request the same instance of MongoEventRepository will be used, even though the new controller class instance still will be created by MVC as a response to each HTTP request. Let's look at the code and note that we've jut changed the behavior of the repository without any modification of controller class. Now you can imagin how much time can we save when IEventRepository is used in 10 controllers(it often happens in real life applications)! This is the power of Dependency Injection containers. They make developers work more efficient.


OPTION 3 - ADD SCOPED
AddScoped is an interesting case. By default scope means that a new instance of MongoEventRepository class will be created once per HTTP request.
It means that the instance will be shared by classes that reference IEventRepository and they are in the scope of one HPTTP request. Can you imagine the situation when one controller references another one and both controllers use IEventRepository? It is still one HTTP request from the client. This scenario results in both controllers using the same instance of MongoEventRepository.


Summary
The built-in service container is not the only option. You can still use Ninject if you wish.
As you could see there are 3 useful methods to configure the mappings between interface and implementation. All 3 are great and can be used depending on your needs.
If your code has too much logic in COntrollers actions, I encourage you to try to extract new service classes and use them the same way I used MongoEventRepository.
Then your code will be easier to test and flexible, cause behavior of services can be changed outside of consuming class.

Komentarze

Popularne posty z tego bloga

Unleash the power of ChatGPT in your C# applications with NGpt - C# OpenAI GPT client

Meet NGpt - OpenAI GPT C# client library that will make your conversations with ChatGPT a breeze! Have you ever been struggling building your own smart AI application in C#? Well, now you can use ChatGpt inside your application! Introducing NGpt, the powerful .NET library that lets you integrate ChatGPT seamlessly into your C# applications. No more nigts spent on building your own AI solitions, no more convoluted logic and building complex business rules - just pure AI bliss. In this blog post, we'll dive into the wonderful world of NGpt and show you how easy it is to use. You might even find a few laughs along the way. The Magic of NGpt NGpt is a transient fault-tolerant .NET 6 OpenAI client that simplifies ChatGPT integration for C# developers. It's like your friendly neighborhood Spider-Man - always there to help you out when you need it most. With just your OpenAI API key, you can start coding AI applications in C# faster than you can say "Peter Parker." Let...

Specflow czyli BDD w praktyce

Dzisiaj pokażę w praktyce w jaki sposób zbieram wymagania korzystając z narzędzia Specflow. Na początku przypomnę nasze historie użtkownika. Potem skonfigurujemy dodatek Specflow Visual Studio. Na końcu pokażę jak wygląda język Gherkin i zaimplementujemy pierwszą historię użytkownika US1. Oto lista funkcjonalności, które będę implementował w aplikacji Perfect Life: US1: Jako użytkownik aplikacji mobilnej chcę ekran logowania aby mieć możliwość zapisywania swoich postępów US2: Jako użytkownik aplikacji mobilnej chcę mieć kalkulator wskaźnika BMI aby móc mierzyć poziom swojej kondycji US3: Jako użytkownik aplikacji mobilnej chcę widzieć wykresy aby móc wizualnie interpretować swoje postępy US4: Jako użytkownik aplikacji mobilnej chcę mieć możliwość rozwiązania quizu, żeby zbadać wskaźnik Body Age US5: Jako użytkownik aplikacji mobilnej chcę pobierać pliki PDF aby mieć dostęp do planów dietetycznych US6: Jako administrator aplikacji chcę zapisywać dane telemetryczne aby móc an...

Up and running with Laravel

Today I'll show you how to start working with Laravel - a modern PHP framework. After reading this article you'll be able to: - Install XAMPP - Configure Virtual Hosts on Apache - Create your first application in Laravel - Run the application - Start coding As a first step I encourage you to visit Laravel.com to get some background knowledge about Laravel. Laravel is a PHP framework which is build on top of the MVC pattern (MVC stands for Model View Controller). You can find general explanation of MVC design pattern with some code examples written in Java here . I assume that you've already installed XAMPP which has version for Linux, Windows and OS X. Personally I'm using Windows in this tutorial but on each operating system it should work similarly. You can get the installer of XAMPP from this page: https://www.apachefriends.org/pl/index.html. When installer prompts you which options you want to install, you need to select Apache and you are free to...