Asp.net 5 web api依赖解析器

时间:2016-02-08 21:16:14

标签: asp.net-mvc asp.net-web-api dependency-injection ninject structuremap

我用asp.net 5 web api模板创建了项目。 startup.cs文件内容是这样的。

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();
    }
}

我想使用像Autofac,StructureMap和Ninject这样的IoC框架。但是如何使用框架更改默认的web api依赖解析器?

例如,StructureMap容器​​设置如下:

        var container = new StructureMap.Container(m=>m.Scan(x =>
                                                             {
              x.TheCallingAssembly(); 
              x.WithDefaultConventions();

                                                             }));

但无法在web api生活中设置它。

2 个答案:

答案 0 :(得分:0)

答案 1 :(得分:0)

查看StructureMap.Dnx项目:

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

用法

该软件包包含一个公共扩展方法Populate。 它曾用于使用一组ServiceDescriptorsIServiceCollection填充StructureMap容器​​。

实施例

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>();
    }
}