Dependency injection best practices for ASP.NET Core MVC 5


Dependency injection is a first-class citizen in ASP.NET Core MVC 5. Part of the new .NET 5, ASP.NET Core MVC 5 is the latest version of Microsoft’s framework for building web apps and APIs using the model-view-controller design pattern.

In this article we’ll take a deep dive into dependency injection in ASP.NET Core MVC 5 as well as learn the best practices that one should follow when working with dependency injection.

To work with the code examples provided in this article, you should have Visual Studio 2019 installed in your system. If you don’t already have a copy, you can download Visual Studio 2019 here.

Create an ASP.NET MVC 5 project in Visual Studio 2019

First off, let’s create an ASP.NET Core project in Visual Studio 2019. Following these steps will create a new ASP.NET Core MVC 5 project in Visual Studio 2019.

  1. Launch the Visual Studio IDE.
  2. Click on “Create new project.”
  3. In the “Create new project” window, select “ASP.NET Core Web App (Model-View-Controller)” from the list of templates displayed.
  4. Click Next.
  5. In the “Configure your new project” window, specify the name and location for the new project.
  6. Optionally check the “Place solution and project in the same directory” check box, depending on your preferences.
  7. Click Next.
  8. In the “Additional Information” window shown next, select .NET 5.0 as the target framework from the drop-down list at the top. Leave the “Authentication Type” as “None” (default).
  9. Ensure that the check boxes “Enable Docker,” “Configure for HTTPS,” and “Enable Razor runtime compilation” are unchecked as we won’t be using any of those features here.
  10. Click Create.

A new ASP.NET Core MVC 5 project will be created. We’ll use this project in the subsequent sections of this article.

Dependency lifetimes in ASP.NET Core MVC 5

When working with ASP.NET Core MVC 5 you must register a service to be able to use it. When you register a service with the container, you can specify the service lifetime. There are three possible lifetimes:

Copyright © 2021 IDG Communications, Inc.



Source link

xandoblogs

An open minded personality.. fun to be with, because of my positive vibes. God fearing, for without God I am nothing.. Moved with compassion when dealing with you, not selfish or self-centered...

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)