【问题标题】:ASP.Core StructureMap ContainerASP.Core StructureMap 容器
【发布时间】:2016-12-04 22:44:39
【问题描述】:

我对 ASP.Core 很陌生。我们有一个项目,我们必须使用依赖注入和 StructureMap。我想知道通过以下方法将Container放入StartUp.cs文件中是否正确。如果是safe 则将IHttpContextAccessor 放入如下配置中:

    public void ConfigureServices(IServiceCollection services) {

        Container container = new Container(expr => {
            expr.For<IDataContextService>().Use<DataContextService>();
            expr.For<IHttpContextAccessor>().Use<HttpContextAccessor>();
            expr.For<ISessionService>().Use<SessionService>();
        });
        services.AddSingleton<IContainer>(container);
    }

【问题讨论】:

    标签: asp.net-core structuremap


    【解决方案1】:

    在 ASP.NET Core 中更改基础 Dependency 容器时,ConfigureServices 需要返回一个IServiceProvider 的实例

    Andew Lock 在他的博客post 中向您展示了如何执行此操作。

    取自他的博文,StructureMap 应该是这样的

    public IServiceProvider ConfigureServices(IServiceCollection services)
    {
        // Add framework services.
        services.AddMvc()
            .AddControllersAsServices();
    
        return ConfigureIoC(services);
    }
    
    public IServiceProvider ConfigureIoC(IServiceCollection services)
        {
            var container = new Container();
    
            container.Configure(config =>
            {
                // Register stuff in container, using the StructureMap APIs...
                config.Scan(_ =>
                {
                    _.AssemblyContainingType(typeof(Startup));
                    _.WithDefaultConventions();
                    _.AddAllTypesOf<IGamingService>();
                    _.ConnectImplementationsToTypesClosing(typeof(IValidator<>));
                });
    
                config.For(typeof(IValidator<>)).Add(typeof(DefaultValidator<>));
                config.For(typeof(ILeaderboard<>)).Use(typeof(Leaderboard<>));
                config.For<IUnitOfWork>().Use(_ => new UnitOfWork(3)).ContainerScoped();
    
                //Populate the container using the service collection
                config.Populate(services);
            });
    
            return container.GetInstance<IServiceProvider>();
    
        }
    }
    

    如果您对使用 Autofac 感兴趣,可以参考 ASP.NET documentation 了解该主题

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-17
      • 2018-11-21
      相关资源
      最近更新 更多