How to use Simple Injector in ASP.NET Core MVC

Maria J. Danford

Dependency injection (also recognised as DI) is a layout sample in which an object gets the objects it relies upon on fairly than making them immediately. Dependency injection facilitates unfastened coupling and encourages testability and easy maintenance. It lets you to improve your implementations without the need of modifying the lessons or interfaces that leverage all those implementations.

Aid for dependency injection is provided in ASP.Web Core. As a result, you can inject both of those framework and application companies into your lessons fairly than count on tightly coupled elements.

Simple Injector is a free of charge, fast, and versatile inversion of command library that is easy to use and configure. It supports .Web Core, Xamarin, Mono, and Common apps and is easily integrated with Website API, MVC, WCF, ASP.Web Core, and many others.

This article talks about how we can leverage Simple Injector to apply dependency injection in ASP.Web Core MVC.

To get the job done with the code illustrations offered in this article, you should really have Visual Studio 2019 mounted in your method. If you really do not presently have a duplicate, you can down load Visual Studio 2019 right here.

Develop an ASP.Web Core MVC project in Visual Studio 2019

To start with off, let us create an ASP.Web Core MVC project in Visual Studio 2019. Pursuing these ways will create a new ASP.Web Core MVC project in Visual Studio 2019 employing .Web 5.

  1. Launch the Visual Studio IDE.
  2. Click on “Create new project.”
  3. In the “Create new project” window, decide on “ASP.Web Core Website App (Model-Look at-Controller)” from the checklist of templates shown.
  4. Click Up coming.
  5. In the “Configure your new project” window, specify the title and area for the new project.
  6. Optionally check the “Place option and project in the very same directory” check box, based on your preferences.
  7. Click Up coming.
  8. In the “Additional Information” window proven future, decide on .Web 5. as the concentrate on framework from the drop-down checklist at the leading. Depart the “Authentication Type” as “None” (default).
  9. Make sure that the check bins “Enable Docker,” “Configure for HTTPS,” and “Enable Razor runtime compilation” are unchecked as we won’t be employing any of all those options right here.
  10. Click Develop.

We’ll use this project to get the job done with Simple Injector in the subsequent sections of this article. Now comply with the ways outlined under to create more controller(s) in your project:

  1. Appropriate-click on on the Controllers option folder.
  2. Pick Incorporate -> Controller.
  3. In the “Add New Scaffolded Item” dialog, decide on API as the template (by default MVC will be selected).
  4. Pick the item “API Controller with browse/write steps.”
  5. Click Incorporate.
  6. In the “Incorporate New Product” dialog proven future, specify a title for your new controller
  7. Click Incorporate

Install Simple Injector NuGet bundle

If you have successfully designed an ASP.Web Core MVC project, the future detail you should really do is include the vital NuGet packages to your project. To do this, decide on the project in the Remedy Explorer window, correct-click on and decide on “Manage NuGet Packages….” In the NuGet Package Supervisor window, lookup for the following bundle and install it.

SimpleInjector.Integration.AspNetCore.Mvc

Alternatively, you can install the bundle through the NuGet Package Supervisor Console as proven under.

PM> Install-Package SimpleInjector.Integration.AspNetCore.Mvc

Simple Injector demo in ASP.Web Core MVC

To show dependency injection employing Simple Injector, we’ll 1st create a company, but only with minimum implementation for the sake of simplicity. Develop a course named DemoService and insert the following code:

namespace SimpleInjectorDemo

    public course DemoService: IDemoService
   
        public string GetMessage()
       
            return "Within GetMessage process..."
       
   

The DemoService course implements the IDemoService interface. In this article is the IDemoService interface for your reference:

namespace SimpleInjectorDemo

    public interface IDemoService
   
        public string GetMessage()
   

Configure Simple Injector in ASP.Web Core MVC

Up coming write the following code snippet in the ConfigureServices process of the Startup course. This sets up simple configuration for integrating Simple Injector with ASP.Web Core MVC.

companies.AddSimpleInjector(container, possibilities =>

    possibilities.AddAspNetCore()
    .AddControllerActivation()
)

You can sign up your company in the ConfigureServices process of the Startup course employing any of the a few strategies of the Life style course:

  • Singleton
  • Scoped
  • Transient

You can write the following code snippet in the ConfigureServices process to sign up an occasion of DemoService.

container.Register(Life style.Singleton)

In this article is the comprehensive code of the ConfigureServices process for your reference:

public void ConfigureServices(IServiceCollection companies)

   companies.AddControllersWithViews()
   companies.AddSimpleInjector(container, possibilities =>
  
        possibilities.AddAspNetCore()
        .AddControllerActivation()
   )
  container.Register(Life style.Singleton)

Now include the following code snippet in the Configure process of the Startup course:

app.UseSimpleInjector(container)

In this article is the comprehensive code of the Configure process for your reference:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env) 
      app.UseSimpleInjector(container)
      if (env.IsDevelopment())
            app.UseDeveloperExceptionPage()
     
      else
            app.UseExceptionHandler("/Dwelling/Error")
     
      app.UseStaticFiles()
      app.UseRouting()
      app.UseAuthorization()
      app.UseEndpoints(endpoints = >
            endpoints.MapControllerRoute(
            title: "default", sample:
            "controller=Dwelling/motion=Index/id?")
      )

Update the Index.cshtml file in ASP.Web Core MVC

Substitute the default supply code of the Index.cshtml file with the following code:

@
    ViewData["Title"] = "Dwelling Site"


   

"@ViewBag.Message"


Use dependency injection in the controller in ASP.Web Core MVC

We’ll now acquire gain of constructor injection in the HomeController to retrieve an occasion of the DemoService. The following code snippet illustrates how you can realize this.

public course HomeController : Controller

   personal IDemoService _demoService
   public HomeController(IDemoService demoService)
  
       _demoService = demoService
  
   public IActionResult Index()
  
      ViewBag.Message = _demoService.GetMessage()
      return Look at()
  
  //Other motion strategies

In this article the Message house of the ViewBag occasion is assigned the text message that is retrieved employing a connect with to the GetMessage process of the DemoService course.

When you execute the application, you will notice the text message “Inside GetMessage process…” shown in the world-wide-web browser as proven in Determine 1 under.

simple injector demo IDG

Determine 1: Dependency injection at get the job done!

Simple Injector removes the typical complexities of an inversion of command library and simplifies how you can use dependency injection in ASP.Web Core.

Last but not least, notice that optionally you could make a connect with to the Verify process of the Container course in the Configure process as proven under:

container.Verify()

In this scenario, the Verify process would throw an exception if there is any error in the configuration you specified.

Copyright © 2021 IDG Communications, Inc.

Next Post

Samsung Tops Global Smartphone Shipments in Q3; Apple Top Earner in Q2 2021: Reports

Samsung topped world wide smartphone shipments in the 3rd quarter of 2021, whilst Apple attained the optimum working gains for the duration of the second quarter of 2021, according to stories by study companies. Even though world wide smartphone shipments saw a 6 per cent drop in Q3 2021 in […]

Subscribe US Now