注入时,IServiceCollection不包含任何元素

时间:2017-10-05 07:18:38

标签: c# asp.net-core

更新 - 修复

  

添加了服务并将它们直接注入构造函数中。   实施服务和应用程序选项注册作为扩展。

我有一个依赖于 IServiceCollection 的标记帮助器,用于请求服务,但即使我在Startup中注册了两个服务,该集合也不包含任何元素。

服务在asp.net核心Web应用程序中注册,该应用程序引用包含标记帮助程序的类库,因此它是两个独立的项目。

我还必须将 IServiceCollection 注册为服务,因为它没有失败(在尝试请求IRazorViewEngine时缺少标记助手中的服务),但我认为该集合已自动注册。将集合添加到同一类型的另一个集合中似乎很奇怪。?

一切都是Core 2.0

Web应用程序, Startup.cs

public Startup(IHostingEnvironment env)
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddEnvironmentVariables();

    Configuration = builder.Build();
}   

public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton<IServiceCollection, ServiceCollection>();
    services.AddSingleton<IRazorViewEngine, RazorViewEngine>();

    services.AddMvc()
        .AddDataAnnotationsLocalization();
}

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

    app.UseStaticFiles();

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Main}/{action=Index}/{id?}");
    });
}

public IConfiguration Configuration { get; }

类库, ViewResourceTagHelper.cs

private IHttpContextAccessor _http;
private IServiceCollection _services;

public ViewResourceTagHelper(IHostingEnvironment env, IServiceCollection services) : base(env)
{           
    using (ServiceProvider provider = services.BuildServiceProvider())
    {
        _http = provider.GetRequiredService<IHttpContextAccessor>();
    }

    _services = services;
}

1 个答案:

答案 0 :(得分:2)

您应该注入IServiceProvider实例而不是IServiceCollection实例:

public ViewResourceTagHelper(IHostingEnvironment env, IServiceProvider provider) : base(env)
{
    _http = provider.GetRequiredService<IHttpContextAccessor>();
}

注入IServiceCollection没有任何意义,因为它已经习惯于配置容器。 IServiceProvider 为您解析服务的容器。 ServiceCollection实例被注入为空,因为DI只是为你启动一个新的空实例。

我不知道,为什么不直接注入IHttpContextAccessor实例?顺便说一句,您还必须为IHttpContextAccessor注册一个实例,因为默认情况下它没有注册:

services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

有关ASP.NET Core中依赖注入的更多信息,请查看the docs

相关问题