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:

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


public interface IHelloWorldService
   string HelloWorld();
public class HelloWorldService : IHelloWorldService
   public string HelloWorld()
      return "Hello world";
public class HelloController : Controller
   private IHelloWorldService _helloService;

   public HelloController(IHelloWorldService helloService)
      _helloService = helloService;

   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)

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


   // 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())



      // Verify Simple Injector configuration




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

Entity Framework Core 2 – DbContext Pools


Entity Framework Core 2 was released on August 14th. It brought new features.

On this article I will explain one of them: DbContext Pools

Normally when a DbContext is injected somewhere by the dependency injection framework, a new instance is created every time. With this, we can have a pool of instances, 128 by default. It is a performance improvement and it is configured like this (console app example):

var serviceProvider = new ServiceCollection()
 .AddDbContextPool<AdventureWorksContext>(options => { //options })
 .AddScoped<IEfQueries, EfQueries>()

.AddDbContext from Entity Framework Core 1 is still implemeted in Entity Framework Core 2.

What kind of improvment to expect ?

Let’s build a Query and let’s see the improvment by using 2 instances of the queries service intantiated by injection dependency system:

public Orders GetOrderById(int id)
   return _context.WorkOrders.Select(
                             x => new Orders
                                Id = x.WorkOrderId,
                                ProductName = x.Product.Name,
                                Quantity = x.OrderQty,
                                Date = x.DueDate
                             }).FirstOrDefault(x => x.Id == id);


// Using AddDbContext 
var efqueriesService1 = serviceProvider.GetService<IEfQueries>();
var efqueriesService2 = serviceProvider.GetService<IEfQueries>();

// Using AddDbContextPool
var efqueriesService1 = serviceProvider.GetService<IEfQueries>();
var efqueriesService2 = serviceProvider.GetService<IEfQueries>();

I executed this serie of execution 20 times and I measured the execution (using Stopwatch object) this:

With AddDbContext:

  • Instance 1: 23 to 29 ms (instantiation + execution)
  • Instance 2: 7 to 9 ms (instantiation + execution)

With AddDbContextPool:

  • Instance 1: 17 to 21 ms (instantiation + execution)
  • Instance 2: 5 to 7 ms (instantiation + execution)

It looks a bit more performant! 😉