Home Ask Login Register

Developers Planet

Your answer is one click away!

bookmarker February 2016

Asp.net 5 web api dependency resolver

I have created project with an asp.net 5 web api template. The startup.cs file content is like this.

public class Startup
    public Startup(IHostingEnvironment env)

    public void ConfigureServices(IServiceCollection services)

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)


I want to use a IoC framework like Autofac, StructureMap and Ninject. But How can I change default web api dependency resolver with a framework?

For example StructureMap container is set like this:

        var container = new StructureMap.Container(m=>m.Scan(x =>


But can not set it in web api life.


Bernd March 2016

Check out the StructureMap.Dnx project:



The package contains a single, public extension method, Populate. It's used to populate a StructureMap container using a set of ServiceDescriptors or an IServiceCollection.


using System;
using Microsoft.Extensions.DependencyInjection;
using StructureMap;

public class Startup
    public IServiceProvider ConfigureServices(IServiceCollection services)

        var container = new Container();

        // You can populate the container instance in one of two ways:

        // 1. Use StructureMap's `Configure` method and call
        //    `Populate` on the `ConfigurationExpression`.

        container.Configure(config =>
            // Register stuff in container, using the StructureMap APIs...


        // 2. Call `Populate` directly on the container instance.
        //    This will internally do a call to `Configure`.

        // Register stuff in container, using the StructureMap APIs...

        // Here we populate the container using the service collection.
        // This will register all services from the collection
        // into the container with the appropriate lifetime.

        // Finally, make sure we return an IServiceProvider. This makes
        // DNX use the StructureMap container to resolve its services.
        return container.GetInstance<IServiceProvider>();

Post Status

Asked in February 2016
Viewed 2,148 times
Voted 5
Answered 2 times


Leave an answer

Quote of the day: live life