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)
    {
        services.AddMvc();
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.UseStaticFiles();

        app.UseMvc();
    }
}

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 =>
                                                             {
              x.TheCallingAssembly(); 
              x.WithDefaultConventions();

                                                             }));

But can not set it in web api life.

Answers



Bernd March 2016

Check out the StructureMap.Dnx project:

https://github.com/structuremap/structuremap.dnx

Usage

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.

Example

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

public class Startup
{
    public IServiceProvider ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
        services.AddWhatever();

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

            config.Populate(services);
        });

        // 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.
        container.Populate(services);

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

Search




Leave an answer