如何将结构图容器配置添加到Web Api启动文件

时间:2017-12-14 16:24:27

标签: asp.net-core .net-core core web.api

我已经设置了一个SctructureMap容器​​(在一个单独的项目中),如下所示:

    public class Container
    {
        public static StructureMap.Container Current { get; private set; }

        public static void InitIoC()
        {
            var container = new StructureMap.Container(
                c =>
                {
                    c.For<AppSettings>().Singleton();
                    c.For<ILogger>().Use<Logger>();
                    c.For<IReminderService>().Use<ReminderService>();
                    ...
                }
       }
    }

我希望在Core 2.0 Web Api中使用此配置。

在我的Startup.cs中,我必须这样做才能使它工作:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
        services.Add(ServiceDescriptor.Transient(typeof(ILogger), typeof(Logger)));
        ... // rewriting what is already configured
    }

如何将此相同配置注入Web Api?

1 个答案:

答案 0 :(得分:1)

你可以试试这个:

 public IServiceProvider ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();                      
        //Create StructureMap container
        var container = new Container(); //This is Structuremap's container class, not your custom class
        container.Configure(config =>
        {
            //Add in your custom structuremap registry
            config.AddRegistry(new Container());
            //Push the .net Core Services Collection into StructureMap
            config.Populate(services);
        });
        //Register dependencies
        services.ConfigureDependencies();
        //Return the service provider
        return container.GetInstance<IServiceProvider>();
    }

我不知道是否有必要,但您可以更改Container课程:

public class Container: Registry
    {
        public Container()
        {               
           c.For<ILogger>().Use<Logger>();
           c.For<IReminderService>().Use<ReminderService>();
           //More mappings
        }
    }