SHARE:

Injection Dependency: Bring your own container in .NET Core Web API, example with Simple Injector

Introduction of Simple Injector

Simple Injector is an easy-to-use Dependency Injection (DI) library for .NET that supports .NET Core, Xamarin, Mono and Universal apps. Simple Injector is easily integrated with frameworks such as Web API, MVC, WCF, ASP.NET Core and many others. It’s easy to implement the dependency injection pattern with loosely coupled components using Simple Injector.

Why Simple Injector? It’s simple to use, free, fast, support advanced generics types, and provide powerful diagnostics services.

If you want to know more about you can check the documentation here: https://simpleinjector.readthedocs.io/en/latest/quickstart.html

Installation of Simple Injector in ASP.NET Core WebAPI

Select and Install SimpleInjector.Integration.AspNetCore.Mvc from “Manage Nuget packages” panel

or type the following command in “Package manager console”:

Install-Package SimpleInjector.Integration.AspNetCore.Mvc -Version 4.0.12

Configuration of Simple Injector in ASP.NET Core WebAPI

  • Import SimpleInjector, SimpleInjector.Lifestyles and SimpleInjector.Integration.AspNetCore.Mvc namespaces
  • Add a Container property in your class Startup.cs
  • Register your service with its appropriate Interface, Simple Injector supports concrete injection (the class without its interface), you can set Lifestyle.Scoped, Lifestyle.Singleton or Lifestyle.Transient
  • Optionnally add Verify method,  (after RegisterMvcControllers method in Configure method) it iterates registered service to check if something is not correct, will throw an exception before any execution of the program
  • Add SimpleInjectorControllerActivator that implements IControllerActivator to provide dependency injection resolution in controllers constructor
  • Then add the extension method UseSimpleInjectorAspNetRequestScoping that ASP.NET requests into Simpleinjector’s scoped lifestyle

Example:

public interface IHelloWorldService
{
   string HelloWorld();
}
public class HelloWorldService : IHelloWorldService
{
   public string HelloWorld()
   {
      return "Hello world";
   }
}
[Route("api/[controller]")]
public class HelloController : Controller
{
   private IHelloWorldService _helloService;

   public HelloController(IHelloWorldService helloService)
   {
      _helloService = helloService;
   }

   [HttpGet]
   public string Get()
   {
      return _helloService.HelloWorld();
   }
}
public class Startup
{
   private Container container = new Container();

   public Startup(IConfiguration configuration)
   {
      Configuration = configuration;
   }

   public IConfiguration Configuration { get; }

   // This method gets called by the runtime. Use this method to add services to the container.
   public void ConfigureServices(IServiceCollection services)
   {
      services.AddMvc();

      // Default lifestyle scoped + async
      // The recommendation is to use AsyncScopedLifestyle in for applications that solely consist of a Web API(or other asynchronous technologies such as ASP.NET Core)
      container.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle();

      // Register services
      container.Register<IHelloWorldService, HelloWorldService>(Lifestyle.Scoped); // lifestyle can set here, sometimes you want to change the default lifestyle like singleton exeptionally

      // Register controllers DI resolution
      services.AddSingleton<IControllerActivator>(new SimpleInjectorControllerActivator(container));

      // Wrap AspNet requests into Simpleinjector's scoped lifestyle
      services.UseSimpleInjectorAspNetRequestScoping(container);

  }

   // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
   public void Configure(IApplicationBuilder app, IHostingEnvironment env)
   {
      if (env.IsDevelopment())
      {
         app.UseDeveloperExceptionPage();
      }

      app.UseMvc();

      container.RegisterMvcControllers(app);

      // Verify Simple Injector configuration
      container.Verify();
   }
}

 

Execution:

 

We did it! we brought our own dependency injection container 🙂

Written by

anthonygiretti

Anthony is a specialist in Web technologies (14 years of experience), in particular Microsoft .NET and learns the Cloud Azure platform. He has received twice the Microsoft MVP award and he is also certified Microsoft MCSD and Azure Fundamentals.
%d bloggers like this: