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

Connect to Azure from command line on Windows

When working with Azure we could go two ways: 1) using Azure portal and work in UI from your web browser 2) Connect to Azure from command line and run commands by typing in text in CMD. I already wrote about option 1 but today I'll show you how to start with option 2 which is Command line. First we need to download MSI installer from Microsoft website After sucessfull instalation you're ready to test az command. Open CMD and type in 'az' Now let's log in with your Azure credentials. Just type in "az login" in cmd. You should be redirected from command line to web browser and prompted for username and account in web browser. When you confirm your identity you'll be presented the screen like this in command line:

Learning e24cloud.com API

Today I'll show you how to use API in order to create virtual server in the cloud directly from your code. We're going write a script in PHP language and use Amazon SDK API to connect with e24cloud.com, which is the biggest and most modern hosting provider in Poland. First we need to install Amazon SDK http://docs.aws.amazon.com/aws-sdk-php/v3/guide/getting-started/installation.html One important note: We can use the latest version of amazon SDK but we also need to do one trick. We'll use signatureV2 instead ov Signaturev4 as e24cloud doesn't support SitnatureV4 yet. You can download it here: https://github.com/aws/aws-sdk-php-v3-bridge We need to download SDK and the bridge which allows us to use Signaturev2 to the same folder, so that require instruction work seamlessly in the form that I provided in the example below. Then go to your admin panel in e24cloud.com to find two values: a key and a secret. In the following code you need to paste those 2 values. ...

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