How to use Simple Injector in ASP.NET Core MVC

Dependency injection (also recognized as DI) is a layout pattern in which an object gets the objects it depends on relatively than developing them straight. Dependency injection facilitates free coupling and encourages testability and easy upkeep. It permits you to transform your implementations devoid of changing the classes or interfaces that leverage people implementations.

Aid for dependency injection is integrated in ASP.Internet Main. As a consequence, you can inject equally framework and software expert services into your classes relatively than depend on tightly coupled components.

Easy Injector is a free, quick, and versatile inversion of command library that is easy to use and configure. It supports .Internet Main, Xamarin, Mono, and Universal apps and is very easily integrated with World wide web API, MVC, WCF, ASP.Internet Main, etc.

This report talks about how we can leverage Easy Injector to employ dependency injection in ASP.Internet Main MVC.

To function with the code examples supplied in this report, you should have Visible Studio 2019 put in in your method. If you really do not presently have a copy, you can download Visible Studio 2019 in this article.

Create an ASP.Internet Main MVC undertaking in Visible Studio 2019

Initial off, let us generate an ASP.Internet Main MVC undertaking in Visible Studio 2019. Next these ways will generate a new ASP.Internet Main MVC undertaking in Visible Studio 2019 using .Internet five.

  1. Start the Visible Studio IDE.
  2. Simply click on “Create new undertaking.”
  3. In the “Create new project” window, find “ASP.Internet Main World wide web App (Product-Check out-Controller)” from the checklist of templates exhibited.
  4. Simply click Future.
  5. In the “Configure your new project” window, specify the title and area for the new undertaking.
  6. Optionally look at the “Place resolution and undertaking in the very same directory” look at box, relying on your preferences.
  7. Simply click Future.
  8. In the “Additional Information” window demonstrated future, find .Internet five. as the focus on framework from the drop-down checklist at the leading. Depart the “Authentication Type” as “None” (default).
  9. Guarantee that the look at packing containers “Enable Docker,” “Configure for HTTPS,” and “Enable Razor runtime compilation” are unchecked as we will not be using any of people attributes in this article.
  10. Simply click Create.

We’ll use this undertaking to function with Easy Injector in the subsequent sections of this report. Now comply with the ways outlined below to generate further controller(s) in your undertaking:

  1. Appropriate-simply click on the Controllers resolution folder.
  2. Pick Incorporate -> Controller.
  3. In the “Add New Scaffolded Item” dialog, find API as the template (by default MVC will be picked).
  4. Pick the product “API Controller with browse/generate steps.”
  5. Simply click Incorporate.
  6. In the “Incorporate New Item” dialog demonstrated future, specify a title for your new controller
  7. Simply click Incorporate

Set up Easy Injector NuGet offer

If you have productively produced an ASP.Internet Main MVC undertaking, the future detail you should do is add the essential NuGet offers to your undertaking. To do this, find the undertaking in the Solution Explorer window, correct-simply click and find “Manage NuGet Packages….” In the NuGet Package deal Manager window, lookup for the pursuing offer and set up it.

SimpleInjector.Integration.AspNetCore.Mvc

Alternatively, you can set up the offer by means of the NuGet Package deal Manager Console as demonstrated below.

PM> Set up-Package deal SimpleInjector.Integration.AspNetCore.Mvc

Easy Injector demo in ASP.Internet Main MVC

To display dependency injection using Easy Injector, we’ll to start with generate a company, but only with minimum implementation for the sake of simplicity. Create a course named DemoService and insert the pursuing code:

namespace SimpleInjectorDemo

    community course DemoService: IDemoService
   
        community string GetMessage()
       
            return "Inside of GetMessage strategy..."
       
   

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

namespace SimpleInjectorDemo

    community interface IDemoService
   
        community string GetMessage()
   

Configure Easy Injector in ASP.Internet Main MVC

Future generate the pursuing code snippet in the ConfigureServices strategy of the Startup course. This sets up essential configuration for integrating Easy Injector with ASP.Internet Main MVC.

expert services.AddSimpleInjector(container, possibilities =>

    possibilities.AddAspNetCore()
    .AddControllerActivation()
)

You can register your company in the ConfigureServices strategy of the Startup course using any of the three solutions of the Way of living course:

  • Singleton
  • Scoped
  • Transient

You can generate the pursuing code snippet in the ConfigureServices strategy to register an occasion of DemoService.

container.Register(Way of living.Singleton)

In this article is the finish code of the ConfigureServices strategy for your reference:

community void ConfigureServices(IServiceCollection expert services)

   expert services.AddControllersWithViews()
   expert services.AddSimpleInjector(container, possibilities =>
  
        possibilities.AddAspNetCore()
        .AddControllerActivation()
   )
  container.Register(Way of living.Singleton)

Now add the pursuing code snippet in the Configure strategy of the Startup course:

app.UseSimpleInjector(container)

In this article is the finish code of the Configure strategy for your reference:

community 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", pattern:
            "controller=Dwelling/motion=Index/id?")
      )

Update the Index.cshtml file in ASP.Internet Main MVC

Replace the default source code of the Index.cshtml file with the pursuing code:

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


   

"@ViewBag.Message"


Use dependency injection in the controller in ASP.Internet Main MVC

We’ll now just take benefit of constructor injection in the HomeController to retrieve an occasion of the DemoService. The pursuing code snippet illustrates how you can realize this.

community course HomeController : Controller

   non-public IDemoService _demoService
   community HomeController(IDemoService demoService)
  
       _demoService = demoService
  
   community IActionResult Index()
  
      ViewBag.Message = _demoService.GetMessage()
      return Check out()
  
  //Other motion solutions

In this article the Message assets of the ViewBag occasion is assigned the textual content message that is retrieved using a simply call to the GetMessage strategy of the DemoService course.

When you execute the software, you’ll notice the textual content message “Inside GetMessage strategy…” exhibited in the world-wide-web browser as demonstrated in Figure one below.

simple injector demo IDG

Figure one: Dependency injection at function!

Easy Injector gets rid of the typical complexities of an inversion of command library and simplifies how you can use dependency injection in ASP.Internet Main.

Eventually, observe that optionally you could make a simply call to the Validate strategy of the Container course in the Configure strategy as demonstrated below:

container.Validate()

In this case, the Validate strategy would toss an exception if there is any mistake in the configuration you specified.

Copyright © 2021 IDG Communications, Inc.