Search code examples
dependency-injectionasp.net-core-mvcsimple-injector

Does registration location differ for Simple Injector in ASP.NET Core MVC?


I'm checking the ASP.NET Core MVC integration documentation of Simple Injector and I see that registrations are done in Configure method of the Startup. Does it matter if they are done in ConfigureServices method instead? Will UseSimpleInjectorAspNetRequestScoping method still work?


Solution

  • Does it matter if they are done in ConfigureServices method instead?

    No, it doesn't. Both in ConfigureServices and Configure there is a reference to the container, so you can use both locations to make registrations.

    The reason the documentation shows that registrations are made during Configure is because at that point in time the built-in configuration system has been built and some services are only available at ConfigureServices.

    Good example of this is the IApplicationBuilder service, which is your entry-point to the ASP.NET Core configuration system. You'll need the IApplicationBuilder to register your MVC controllers and View Components in Simple Injector.

    Will UseSimpleInjectorAspNetRequestScoping method still work?

    No, it won't. UseSimpleInjectorAspNetRequestScoping is an extension method on IApplicationBuilder, which is only available during ConfigureServices.

    The UseSimpleInjectorAspNetRequestScoping extension method on IApplicationBuilder has been deprecated with the release of v4. Instead, a new UseSimpleInjectorAspNetRequestScoping overload on IServiceCollection should be used instead, which means that UseSimpleInjectorAspNetRequestScoping should now actually be called inside ConfigureServices instead of Configure:

    public void ConfigureServices(IServiceCollection services) {
        services.UseSimpleInjectorAspNetRequestScoping(container);
    
        // more code here
    }