Search code examples
asp.net-mvcasp.net-web-apisimple-injector

Simple Injector with MVC and WebAPI


I have a C# project that includes both WebAPI and MVC controllers with which I would like to use Simple Injector. The Simple Injector documentation at https://simpleinjector.readthedocs.io/en/latest/mvcintegration.html shows the Application_Start method for MVC as

protected void Application_Start(object sender, EventArgs e) {
    // Create the container as usual.
    var container = new Container();
    container.Options.DefaultScopedLifestyle = new WebRequestLifestyle();

    // Register your types, for instance:
    container.Register<IUserRepository, SqlUserRepository>(Lifestyle.Scoped);

    // This is an extension method from the integration package.
    container.RegisterMvcControllers(Assembly.GetExecutingAssembly());

    container.Verify();

    DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));
}

but https://simpleinjector.readthedocs.io/en/latest/webapiintegration.html shows the following for WebAPI

protected void Application_Start() {
    // Create the container as usual.
    var container = new Container();
    container.Options.DefaultScopedLifestyle = new WebApiRequestLifestyle();

    // Register your types, for instance using the scoped lifestyle:
    container.Register<IUserRepository, SqlUserRepository>(Lifestyle.Scoped);

    // This is an extension method from the integration package.
    container.RegisterWebApiControllers(GlobalConfiguration.Configuration);

    container.Verify();

    GlobalConfiguration.Configuration.DependencyResolver =
    new SimpleInjectorWebApiDependencyResolver(container);

    // Here your usual Web API configuration stuff.
}

How can I code Application_Start please so I can use Simple Injector in WebAPI and MVC controllers?


Solution

  • you could just put the code together like this:

    protected void Application_Start(object sender, EventArgs e) {
        var container = new Container();
        container.Options.DefaultScopedLifestyle = new WebRequestLifestyle();
    
        container.Register<IUserRepository, SqlUserRepository>(Lifestyle.Scoped);
    
        // User MVC integration
        container.RegisterMvcControllers(Assembly.GetExecutingAssembly());
    
        // Use Web API integration
        container.RegisterWebApiControllers(GlobalConfiguration.Configuration);
    
        container.Verify();
    
        // Plug in Simple Injector into MVC
        DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));
    
        // Plug in Simple Injector into Web API
        GlobalConfiguration.Configuration.DependencyResolver =
            new SimpleInjectorWebApiDependencyResolver(container);
    }