如何在 ASP.NET Core 1.0 的 DI 中的 Startup 类中添加 IHttpContextAccessor?

     2023-03-09     121

关键词:

【中文标题】如何在 ASP.NET Core 1.0 的 DI 中的 Startup 类中添加 IHttpContextAccessor?【英文标题】:How to add IHttpContextAccessor in the Startup class in the DI in ASP.NET Core 1.0? 【发布时间】:2016-11-06 04:16:21 【问题描述】:

在 ASP.NET Core RC 1 中,我使用以下代码检索上下文的值(页面的完整地址)。然后我在配置中记录了这个值。

public class Startup

        public IConfigurationRoot Configuration  get; set; 
        private IHostingEnvironment CurrentEnvironment  get; set; 
        private IHttpContextAccessor HttpContextAccessor  get; set; 
        public Startup(IHostingEnvironment env,
                IHttpContextAccessor httpContextAccessor)
                            
                var builder = new ConfigurationBuilder()
                    .SetBasePath(env.ContentRootPath)
                    .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                    .AddJsonFile($"appsettings.env.EnvironmentName.json", optional: true);
    
                if (env.IsDevelopment())
                
                    builder.AddUserSecrets();
                
                builder.AddEnvironmentVariables();
                Configuration = builder.Build();
                CurrentEnvironment = env;
                HttpContextAccessor = httpContextAccessor;
            
        public void ConfigureServices(IServiceCollection services)
        
        ...
        
        services.AddOptions();
        services.Configure<WebAppSettings>(configuration);
        services.Configure<WebAppSettings>(settings =>
        
            ...
            settings.WebRootPath = CurrentEnvironment.WebRootPath;
            settings.DomainUrl = HttpContextAccessor.HttpContext.Request.Host.ToUriComponent();
        );
        
   

现在我开始在 ASP.NET Core 1.0 上更新项目。但在网站启动期间,我收到以下错误:

System.InvalidOperationException 无法解析类型的服务 'Microsoft.AspNetCore.Http.IHttpContextAccessor' 尝试 激活“MyProject.Startup”。

在 Microsoft.Extensions.Internal.ConstructorMatcher.CreateInstance(IServiceProvider 提供者)在 Microsoft.Extensions.Internal.ActivatorUtilities.CreateInstance(IServiceProvider 提供者,类型 instanceType,Object[] 参数)在 Microsoft.Extensions.Internal.ActivatorUtilities.GetServiceOrCreateInstance(IServiceProvider 提供者,类型类型)在 Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetServiceOrCreateInstance(IServiceProvider 提供者,类型类型)在 Microsoft.AspNetCore.Hosting.Internal.StartupLoader.LoadMethods(IServiceProvider 服务,类型 startupType,字符串 environmentName)在 Microsoft.AspNetCore.Hosting.c__DisplayClass1_0.b__1(IServiceProvider sp) 在 Microsoft.Extensions.DependencyInjection.ServiceLookup.FactoryService.Invoke(ServiceProvider 提供者)在 Microsoft.Extensions.DependencyInjection.ScopedCallSite.Invoke(ServiceProvider 提供者)在 Microsoft.Extensions.DependencyInjection.SingletonCallSite.Invoke(ServiceProvider 提供者)在 Microsoft.Extensions.DependencyInjection.c__DisplayClass12_0.b__0(ServiceProvider 提供者)在 Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(类型 服务类型)在 Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider 提供者,类型 serviceType) 在 Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider 提供者)在 Microsoft.AspNetCore.Hosting.Internal.WebHost.EnsureStartup() 在 Microsoft.AspNetCore.Hosting.Internal.WebHost.EnsureApplicationServices() 在 Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication()

.NET Framework X64 v4.0.30319.42000 | Microsoft.AspNetCore.Hosting 版本 1.0.0-rtm-21431 |微软视窗 6.1.7601 S

应用启动时如何获取新版本的IHttpContextAccessor?

【问题讨论】:

如果您查看 .Net Core 的重大更改,您会发现默认情况下不再注册 IHttpContextAccessor。 github.com/aspnet/Hosting/issues/793 【参考方案1】:

它不再是默认服务。您必须在 Startup.cs 中配置它

services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.TryAddSingleton<IActionContextAccessor, ActionContextAccessor>();

更新:在 ASP.NET Core 2.1 中,添加了 the AddHttpContextAccessor helper extension method 以使用正确的生命周期(单例)正确注册 IHttpContextAccessor。所以,在 ASP.NET Core 2.1 及以上版本中,代码应该是

services.AddHttpContextAccessor();
services.TryAddSingleton<IActionContextAccessor, ActionContextAccessor>();

来源:https://github.com/aspnet/Hosting/issues/793

【讨论】:

官宣:github.com/aspnet/Announcements/issues/190 一个问题不应该是AddTransient,因为它是针对请求的? @Ruchan 你有没有得到这个答案?它应该是单例的还是瞬态的? @Reft 我用过单例。这是有关此github.com/aspnet/Hosting/issues/793 的更多信息,请阅读 davidfowl 的答案 @Ruchan 将IHttpContextAccessor 注册为单例是可行的,因为它使用AsyncLocal&lt;T&gt; 来存储HttpContext。【参考方案2】:

你可以这样添加。

services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

【讨论】:

【参考方案3】:

.Net 6 可以这样添加

builder.Services.AddSingleton();

【讨论】:

如何在 ASP.NET Core 1.0 中获取 bin 文件夹

】如何在ASP.NETCore1.0中获取bin文件夹【英文标题】:HowtogetbinfolderinASP.NETCore1.0【发布时间】:2016-02-2018:16:15【问题描述】:在asp.netcore1.0中添加了很多功能。但是没有办法获得Bin文件夹路径。谁能知道我们如何获取asp.netcore1.0应用... 查看详情

在 asp.net core razor 页面中使用带有部分视图的 DI [重复]

】在asp.netcorerazor页面中使用带有部分视图的DI[重复]【英文标题】:UsingaDIwithpartialviewsinasp.netcorerazorpages[duplicate]【发布时间】:2021-05-0707:36:12【问题描述】:使用以下行正在使用部分视图(否则工作完全正常;当不使用DI时):&... 查看详情

如何在 ASP.NET Core 1.0 应用程序中使用 SqlServer.Types / 空间类型

】如何在ASP.NETCore1.0应用程序中使用SqlServer.Types/空间类型【英文标题】:HowtouseSqlServer.Types/spatialtypeswithinASP.NETCore1.0application【发布时间】:2016-12-1822:15:03【问题描述】:我们的一个类库使用Microsoft空间类型,例如DbGeography。在没... 查看详情

在 ASP.NET Core 1.0 上处理大文件上传

...传,这成为一个问题,因为它既慢又需要更多内存。有关如何禁用请求缓冲的ASP.NETther 查看详情

如何将项目引用添加到 ASP.NET Core 1.0 MVC 项目

】如何将项目引用添加到ASP.NETCore1.0MVC项目【英文标题】:HowtoaddprojectreferencetoASP.NETCore1.0MVCproject【发布时间】:2016-11-0115:10:30【问题描述】:我在解决方案X中有一个ASP.NETCore1.0MVC应用程序,在解决方案Y中有一些常见项目(.net4.5... 查看详情

使用默认 ASP.NET Core DI 容器在 Service Fabric 上设置依赖注入

】使用默认ASP.NETCoreDI容器在ServiceFabric上设置依赖注入【英文标题】:SetupDependencyInjectiononServiceFabricusingdefaultASP.NETCoreDIcontainer【发布时间】:2019-06-0816:20:20【问题描述】:我想使用ASP.NETCore的默认DI容器为我的ServiceFabric项目设置D... 查看详情

带有 ASP.NET Core DI 的 MediatR

】带有ASP.NETCoreDI的MediatR【英文标题】:MediatRwithASP.NETCoreDI【发布时间】:2016-05-2609:30:20【问题描述】:我正在使用新的ASP.NETCore,目前正在创建一个我想从JavaScript前端调用的API。我想使用中介者模式来减少耦合,我从JimmyBogard... 查看详情

在 asp.net core 1.0 上读取一个 excel 文件

】在asp.netcore1.0上读取一个excel文件【英文标题】:Readanexcelfileonasp.netcore1.0【发布时间】:2017-03-2606:31:16【问题描述】:您好,我正在尝试在我的asp.net项目中上传和读取一个excel文件,但我找到的所有文档都是针对ASPMVC5的。我的... 查看详情

替换 ASP.NET Core 内置 DI 容器中的服务注册?

】替换ASP.NETCore内置DI容器中的服务注册?【英文标题】:ReplaceserviceregistrationinASP.NETCorebuilt-inDIcontainer?【发布时间】:2017-09-2107:02:10【问题描述】:让我们考虑Startup.ConfigureServices中的服务注册:publicvoidConfigureServices(IServiceCollecti... 查看详情

ASP.NET Core 2 - 身份 - 自定义角色的 DI 错误

】ASP.NETCore2-身份-自定义角色的DI错误【英文标题】:ASP.NETCore2-Identity-DIerrorswithcustomRoles【发布时间】:2018-01-3000:39:29【问题描述】:我的Startup.cs中有这段代码:services.AddDbContext<ApplicationDbContext>(options=>options.UseSqlServer(Confi... 查看详情

如何在 ASP.NET Core 中使控制器作用域或单例而不是瞬态?

】如何在ASP.NETCore中使控制器作用域或单例而不是瞬态?【英文标题】:HowtomakecontrollersscopedorsingletoninsteadoftransientinASP.NETCore?【发布时间】:2020-10-2815:17:07【问题描述】:我现在默认情况下,控制器注册到具有瞬态生命周期的默... 查看详情

ASP.NET Core 2 - 多个 Azure Redis 缓存服务 DI

】ASP.NETCore2-多个AzureRedis缓存服务DI【英文标题】:ASP.NETCore2-MultipleAzureRedisCacheservicesDI【发布时间】:2017-10-1811:21:48【问题描述】:在ASP.NETCore2中,我们可以像这样添加AzureRedis缓存:services.AddDistributedRedisCache(config=>config.Configur... 查看详情

ASP.Net Core DI 公司上下文提供者? [复制]

】ASP.NetCoreDI公司上下文提供者?[复制]【英文标题】:ASP.NetCoreDIcompanycontextprovider?[duplicate]【发布时间】:2019-10-0411:21:06【问题描述】:我正在使用ASP.NETCore3实现一个webapi。在后端,我们有许多具有完全相同架构/表等的公司数据... 查看详情

从静态工厂类访问 ASP.NET Core DI 容器

】从静态工厂类访问ASP.NETCoreDI容器【英文标题】:AccessingASP.NETCoreDIContainerFromStaticFactoryClass【发布时间】:2016-11-1513:58:07【问题描述】:我根据JamesStill的博客文章Real-WorldPubSubMessagingwithRabbitMQ创建了一个具有RabbitMQ订阅者的ASP.NETC... 查看详情

如何在 ASP.NET Core 2.1 中的计时器上运行 BackgroundService

】如何在ASP.NETCore2.1中的计时器上运行BackgroundService【英文标题】:HowtorunBackgroundServiceonatimerinASP.NETCore2.1【发布时间】:2019-05-1215:54:03【问题描述】:我想在ASP.NETCore2.1中运行后台作业。它必须每2小时运行一次,并且需要访问我... 查看详情

如何配置 ASP.NET Core 1.0 以使用本地 IIS 而不是 IIS Express?

】如何配置ASP.NETCore1.0以使用本地IIS而不是IISExpress?【英文标题】:HowtoconfigureASP.NETCore1.0touseLocalIISinsteadofIISExpress?【发布时间】:2016-12-0120:20:23【问题描述】:如何设置.NetCore1.0项目以在调试时使用LocalIIS而不是IISExpress?我尝试... 查看详情

ASP.NET Core 1.0(前 MVC 6)中的单元测试路由

...随着ASP.NETCore1.0(前MVC6/ASP.NET5.0)的架构发生重大变化,如何对路由进行单元测试?例如,我喜欢这样的库(对于https://github.com/AnthonySteele/MvcRout 查看详情

Ninject 中的 .NET Core DI 范围生命周期

】Ninject中的.NETCoreDI范围生命周期【英文标题】:.NETCoreDIscopelifetimeinNinject【发布时间】:2018-12-1207:20:37【问题描述】:编辑:由于许多用户错误地将其视为ASP.NET特定问题。请注意,我的应用程序不是Web应用程序,并且我没有使... 查看详情