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

Aplikacja 'Perfect Life' - planowanie funkcjonalności

W poprzednim wpisie przedstawiłem budowę historii użytkownika(ang. User Story). Dzisiaj korzystając z tego narzędzia zaplanujemy kilka funkcjonalności. Czas na zaplanowanie funkcjonalności aplikacji mobilnej Perfect Life. Aplikacja jest tworzona w oparciu o technologię Xamarin.Forms. Póki co jednak abstrahując od rozwiązań technologicznych skupimy się na funkcjonalnościach. Dobre planowanie swojej pracy to podstawa sukcesu każdego projektu programistycznego. 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ó...

Dziś Premiera Visual Studio 2017

Dzisiaj ważny dzień dla programistów .NET. Premiera środowiska programistycznego Visual Studio 2017. Relację na żywo można oglądać tutaj: https://launch.visualstudio.com/ Jutro będzie dzień warsztatów, w których możemy wziąć udział online. Nowe VS możemy pobrać ze strony: https://www.visualstudio.com/ Co ciekawe pobierając VS teraz otrzymasz 60 dni darmowego dostępu do Xamarin University. To ważne jeśli chcesz się nauczyć tworzyć aplikacje mobilne. Co nowego? Lepsza integracja z VSTS Live unit testing - zwróćmy uwagę na ikony po lewej stronie: Dodatkowe ikony: Wyszukiwanie metod po fragmencie nazwy. Code suggestions, czyli podpowiedzi na temat najlepszych praktyk w trakcie pisania kodu. Możemy zdefiniować własne sugestie dot. kodu i dodac własne konfiguracje edytora kodu: Dodatkowo pojawiły się dodatkowe ikony, dzięki którym łatwo się zorientować gdzie kończy się klasa, a gdzie namespace. Wygląda to nieźle. Inne usprawnienia o których mówił Scott Hanselman...

ASP.NET Core MVC - wdrożenie na Linuxie krok po kroku

Dzisiaj skupimy się na wdrożeniu aplikacji ASP.NET Core MVC. Po przeczytaniu tego artykułu będziesz potrafił uruchomić swoją pierwszą aplikację ASP.NET Core na maszynie wirtualnej z systemem Ubuntu 14. Załóżmy, że mamy nasza aplikację gotową i chcemy ją uruchomić. Jak najłatwiej to zrobić? Podczas debugowania możemy roboczo wykorzystać Visual Studio do uruchomienia aplikacji na IIS Express. Jednak w warunkach produkcyjnych kiedy chcemy wdrożyć aplikację na systemie Linux, musimy poszukać innego rozwiązania. Dlaczego? Bo Linux nie będzie obsługiwał ani visual Studio ani IIS Express, ponadto jeśli korzystamy z Continuous Deployment, to chcemy wdrożenie robić z poziomu konsoli. Jak pisałem w poprzednich postach, wraz z nadejściem ASP.NET Core MVC, mamy możliwość wdrażania aplikacji napisanych w C# na platformie Linux. To niezwykle istotne, bo przynosi ogromne korzyści, choćby dlatego, że ceny hostingu są kilka razy niższe dla maszyn z Linuxem niż z Windowsem. 1) Framework-depen...