[英]Cannot access a disposed object. Object name: 'IServiceProvider' error in AspNet Core/EF Core project
[英].Net Core 2.1 - Cannot access a disposed object.Object name: 'IServiceProvider'
我剛剛將 .NET Core 2.0 遷移到 .NET Core 2.1。 一切順利,但是當我現在嘗試登錄時,出現以下錯誤:
- $exception {System.ObjectDisposedException:無法訪問已處置的 object。Object 名稱:'IServiceProvider'。
這發生在這段代碼中:
public class AppContractResolver : DefaultContractResolver
{
private readonly IServiceProvider _services;
public AppContractResolver(IServiceProvider services)
{
_services = services;
}
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
var httpContextAccessor = _services.GetService<IHttpContextAccessor>();
var user = httpContextAccessor.HttpContext.User;
List<JsonProperty> properies = base.CreateProperties(type, memberSerialization).ToList();
properies = FilterOneClaimGranted(type, properies, user);
return properies;
}
它發生在這條線上:
var httpContextAccessor = _services.GetService<IHttpContextAccessor>();
這確實適用於 .NET Core 2.0
我曾嘗試將HttpContextAccessor
添加到我的啟動項中,但這沒有用。
那么,我該如何解決這個問題?
如果您需要更多代碼,請告訴我。 我很樂意提供更多,但我不知道你可能需要或不需要什么,因此我沒有添加很多代碼。
編輯
我添加了services.AddHttpContextAccessor();
到我的初創公司,但這似乎不起作用。 仍然收到錯誤。
編輯 2:
完整的堆棧跟蹤:
- $exception {System.ObjectDisposedException: Cannot access a disposed object.
Object name: 'IServiceProvider'.
at Microsoft.Extensions.DependencyInjection.ServiceLookup.ThrowHelper.ThrowObjectDisposedException()
at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type serviceType)
at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetService[T](IServiceProvider provider)
at WebAPI.Extensions.AppContractResolver.CreateProperties(Type type, MemberSerialization memberSerialization) in C:\Users\luukw\Desktop\stage\blacky-api\Blacky\Extensions\Resolver\AppContractResolver.cs:line 25
at Newtonsoft.Json.Serialization.DefaultContractResolver.CreateObjectContract(Type objectType)
at Newtonsoft.Json.Serialization.DefaultContractResolver.CreateContract(Type objectType)
at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)
at Newtonsoft.Json.Serialization.DefaultContractResolver.ResolveContract(Type type)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.GetContractSafe(Type type)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)
at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)
at Newtonsoft.Json.JsonSerializer.Deserialize(JsonReader reader, Type objectType)
at Microsoft.AspNetCore.Mvc.Formatters.JsonInputFormatter.ReadRequestBodyAsync(InputFormatterContext context, Encoding encoding)} System.ObjectDisposedException
就我而言,問題出在Startup.cs
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider services)
{
var svc = services.GetService<IService>(); // <-- exception here
}
只需將services.GetService<>()
替換為app.ApplicationServices.GetService<>()
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
var svc = app.ApplicationServices.GetService<IService>(); // no exception
}
希望能幫助到你
我建議不要調用services.GetService<IHttpContextAccessor>()
, IHttpContextAccessor
將IHttpContextAccessor
注入構造函數並使用私有字段來存儲值。
public AppContractResolver(IServiceProvider services,
IHttpContextAccessor httpContextAccessor)
{
_services = services;
this.httpContextAccessor = httpContextAccessor;
}
此外 HttpContextAccessor 必須手動注冊。 在Startup.cs
RegisterServices 添加, services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
如果您創建任何瞬態服務,例如 services.AddTransient...,那么 .net core 將處置服務提供者。 這是 .net core 2.2 的錯誤。
對我來說,它適用於:
public void ConfigureServices(IServiceCollection services)
{
…
services.AddHttpContextAccessor();
…
}
進而:
public void Configure(IApplicationBuilder app, IHttpContextAccessor accessor)
{
...
...accessor.HttpContext.RequestService
...
}
我收到了這個錯誤,花了很長時間才解決,所以我要把它貼在這里。
這是引發錯誤的代碼:
using var context = this.DbFactory.CreateDbContext();
SqlParameter[] parameter =
{
new SqlParameter("@ord_cust_id", ordCustId)
};
products = await context.GetProduct.FromSqlRaw<ProductEntity>($"{spName} @ord_cust_id", parameter).AsNoTracking().ToListAsync();
拋出的異常在最后一行。 由於上下文是由 DbFactory 創建的,因此沒有任何意義,因此無法處理它。
找了好久,發現DbFactory的作用域是“Transient”,改成Singleton,異常就解決了。
這是啟動時的代碼:
services.AddDbContextFactory<CDSEntities>(options =>
{
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
}, ServiceLifetime.Singleton); //changed to Singlton instead of Transient
在我的例子中,我在 rest API 方法上沒有異步等待,所以它在調用結束之前處理 IServiceProvider。
我只是將.NET Core 2.0遷移到.NET Core 2.1。 一切正常,但是當我現在嘗試登錄時,出現以下錯誤:
- $ exception {System.ObjectDisposedException:無法訪問已處置的對象。 對象名稱:“ IServiceProvider”。
這在以下代碼中發生:
public class AppContractResolver : DefaultContractResolver
{
private readonly IServiceProvider _services;
public AppContractResolver(IServiceProvider services)
{
_services = services;
}
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
var httpContextAccessor = _services.GetService<IHttpContextAccessor>();
var user = httpContextAccessor.HttpContext.User;
List<JsonProperty> properies = base.CreateProperties(type, memberSerialization).ToList();
properies = FilterOneClaimGranted(type, properies, user);
return properies;
}
它發生在這一行:
var httpContextAccessor = _services.GetService<IHttpContextAccessor>();
這確實適用於.NET Core 2.0
我嘗試將HttpContextAccessor
添加到我的啟動中,但這沒有用。
那么,我該如何解決呢?
讓我知道您是否需要更多代碼。 我會很樂意提供更多,但我不知道您可能需要或不需要什么,因此我沒有添加很多代碼。
編輯
我已經添加了services.AddHttpContextAccessor();
到我的初創公司,但這似乎不起作用。 仍然出現錯誤。
編輯2:
完整的堆棧跟蹤:
- $exception {System.ObjectDisposedException: Cannot access a disposed object.
Object name: 'IServiceProvider'.
at Microsoft.Extensions.DependencyInjection.ServiceLookup.ThrowHelper.ThrowObjectDisposedException()
at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type serviceType)
at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetService[T](IServiceProvider provider)
at WebAPI.Extensions.AppContractResolver.CreateProperties(Type type, MemberSerialization memberSerialization) in C:\Users\luukw\Desktop\stage\blacky-api\Blacky\Extensions\Resolver\AppContractResolver.cs:line 25
at Newtonsoft.Json.Serialization.DefaultContractResolver.CreateObjectContract(Type objectType)
at Newtonsoft.Json.Serialization.DefaultContractResolver.CreateContract(Type objectType)
at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)
at Newtonsoft.Json.Serialization.DefaultContractResolver.ResolveContract(Type type)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.GetContractSafe(Type type)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)
at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)
at Newtonsoft.Json.JsonSerializer.Deserialize(JsonReader reader, Type objectType)
at Microsoft.AspNetCore.Mvc.Formatters.JsonInputFormatter.ReadRequestBodyAsync(InputFormatterContext context, Encoding encoding)} System.ObjectDisposedException
在Startup ➢ ConfigureServices
方法中嘗試獲取服務時,我遇到了類似的異常:
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<INotification>(provider =>
{
var hubContext = (IHubContext<NotificationHub>)provider
.GetService(typeof(IHubContext<NotificationHub>));
// ↓↓↓ Exception: cannot access a disposed object. Object name: 'IServiceProvider'.
var mediator = (IMediator)provider.GetService(typeof(IMediator));
hubContext.SetListener(() =>
mediator.Send(new ...);
...
});
}
...
}
僅供參考: NotificationHub
是我實現自定義INotificaiton
服務的自定義通知類。
通過創建本地范圍服務解決了問題:
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<INotification>(provider =>
{
var hubContext = (IHubContext<NotificationHub>)provider
.GetService(typeof(IHubContext<NotificationHub>));
var myScope = provider.CreateScope(); // <<< creating a scoped sertvice
var mediator = (IMediator)myScope.ServiceProvider.GetService(typeof(IMediator));
hubContext.SetListener(() =>
mediator.Send(new ...);
...
});
}
...
}
就我而言,調用方方法中缺少“await”運算符。
public async Task<OrderResponse> CreateOrder(){
//Do something
var response = **await** CreateOrderItem();
return response;
}
public async Task<ItemResponse> CreateOrderItem(){
//Do something
}
CreateOrder() 中缺少“await”
我在.Net中編寫的一個應用程序(esims)遇到類似的問題,程序員說它需要.Net 2,現在我們在工作的許多計算機都可以在Windows 7和10 Pro上正常工作,但是在我的筆記本電腦上Windows 10 Pro全新安裝,並且在進行所有更新並在程序功能中進行了所有設置以激活.Net 3.5 Framework(包括.Net 2和3)之后,它無法向我顯示報告。 該應用程序正確啟動,加載數據庫,但是當我要求提供報告時說:
See the end of this message for details on invoking
just-in-time (JIT) debugging instead of this dialog box.
************** Exception Text **************
System.ObjectDisposedException: Cannot access a disposed object.
Object name: 'ReportViewer'.
at Microsoft.Reporting.WinForms.ReportViewer.get_CurrentReport()
at Microsoft.Reporting.WinForms.ReportViewer.Clear()
at Microsoft.Reporting.WinForms.ReportViewer.RefreshReport(Int32 targetPage, PostRenderArgs postRenderArgs)
at Microsoft.Reporting.WinForms.ReportViewer.RefreshReport()
at Universum_Client.ReportForms.frmPrev.YVA4YnrEuQZ(Object , EventArgs )
at System.EventHandler.Invoke(Object sender, EventArgs e)
at System.Windows.Forms.Form.OnLoad(EventArgs e)
at System.Windows.Forms.Form.OnCreateControl()
at System.Windows.Forms.Control.CreateControl(Boolean fIgnoreVisible)
at System.Windows.Forms.Control.CreateControl()
at System.Windows.Forms.Control.WmShowWindow(Message& m)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ScrollableControl.WndProc(Message& m)
at System.Windows.Forms.ContainerControl.WndProc(Message& m)
at System.Windows.Forms.Form.WmShowWindow(Message& m)
at System.Windows.Forms.Form.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
************** Loaded Assemblies **************
mscorlib
Assembly Version: 2.0.0.0
Win32 Version: 2.0.50727.9148 (WinRelRS6.050727-9100)
CodeBase: file:///C:/Windows/Microsoft.NET/Framework/v2.0.50727/mscorlib.dll
----------------------------------------
eSims
Assembly Version: 1.0.7102.22332
Win32 Version: 1.0.7102.22332
CodeBase: file:///C:/Program%20Files%20(x86)/UAIC/eSIMS/eSims.exe
----------------------------------------
MessageBoxGC
Assembly Version: 1.0.6904.25481
Win32 Version: 1.0.7102.22332
CodeBase: file:///C:/Program%20Files%20(x86)/UAIC/eSIMS/eSims.exe
----------------------------------------
System.Windows.Forms
Assembly Version: 2.0.0.0
Win32 Version: 2.0.50727.9136 (WinRelRS6.050727-9100)
CodeBase: file:///C:/Windows/assembly/GAC_MSIL/System.Windows.Forms/2.0.0.0__b77a5c561934e089/System.Windows.Forms.dll
----------------------------------------
System
Assembly Version: 2.0.0.0
Win32 Version: 2.0.50727.9147 (WinRelRS6.050727-9100)
CodeBase: file:///C:/Windows/assembly/GAC_MSIL/System/2.0.0.0__b77a5c561934e089/System.dll
----------------------------------------
System.Drawing
Assembly Version: 2.0.0.0
Win32 Version: 2.0.50727.9136 (WinRelRS6.050727-9100)
CodeBase: file:///C:/Windows/assembly/GAC_MSIL/System.Drawing/2.0.0.0__b03f5f7f11d50a3a/System.Drawing.dll
----------------------------------------
Accessibility
Assembly Version: 2.0.0.0
Win32 Version: 2.0.50727.9136 (WinRelRS6.050727-9100)
CodeBase: file:///C:/Windows/assembly/GAC_MSIL/Accessibility/2.0.0.0__b03f5f7f11d50a3a/Accessibility.dll
----------------------------------------
Universum_Library
Assembly Version: 1.0.7102.22323
Win32 Version: 1.0.7102.22332
CodeBase: file:///C:/Program%20Files%20(x86)/UAIC/eSIMS/eSims.exe
----------------------------------------
System.Runtime.Remoting
Assembly Version: 2.0.0.0
Win32 Version: 2.0.50727.9136 (WinRelRS6.050727-9100)
CodeBase: file:///C:/Windows/assembly/GAC_MSIL/System.Runtime.Remoting/2.0.0.0__b77a5c561934e089/System.Runtime.Remoting.dll
----------------------------------------
System.Configuration
Assembly Version: 2.0.0.0
Win32 Version: 2.0.50727.9136 (WinRelRS6.050727-9100)
CodeBase: file:///C:/Windows/assembly/GAC_MSIL/System.Configuration/2.0.0.0__b03f5f7f11d50a3a/System.Configuration.dll
----------------------------------------
System.Xml
Assembly Version: 2.0.0.0
Win32 Version: 2.0.50727.9136 (WinRelRS6.050727-9100)
CodeBase: file:///C:/Windows/assembly/GAC_MSIL/System.Xml/2.0.0.0__b77a5c561934e089/System.Xml.dll
----------------------------------------
System.Data
Assembly Version: 2.0.0.0
Win32 Version: 2.0.50727.9136 (WinRelRS6.050727-9100)
CodeBase: file:///C:/Windows/assembly/GAC_32/System.Data/2.0.0.0__b77a5c561934e089/System.Data.dll
----------------------------------------
Microsoft.ReportViewer.WinForms
Assembly Version: 11.0.0.0
Win32 Version: 11.0.3442.2 ((SQL11_SP1_RS_Dev12-RTM).140611-0541 )
CodeBase: file:///C:/Program%20Files%20(x86)/UAIC/eSIMS/Microsoft.ReportViewer.WinForms.DLL
----------------------------------------
System.Core
Assembly Version: 3.5.0.0
Win32 Version: 3.5.30729.9135 built by: WinRelRS6
CodeBase: file:///C:/Windows/assembly/GAC_MSIL/System.Core/3.5.0.0__b77a5c561934e089/System.Core.dll
----------------------------------------
Microsoft.ReportViewer.Common
Assembly Version: 11.0.0.0
Win32 Version: 11.0.3442.2 ((SQL11_SP1_RS_Dev12-RTM).140611-0541 )
CodeBase: file:///C:/Program%20Files%20(x86)/UAIC/eSIMS/Microsoft.ReportViewer.Common.DLL
----------------------------------------
System.Web.Services
Assembly Version: 2.0.0.0
Win32 Version: 2.0.50727.9136 (WinRelRS6.050727-9100)
CodeBase: file:///C:/Windows/assembly/GAC_MSIL/System.Web.Services/2.0.0.0__b03f5f7f11d50a3a/System.Web.Services.dll
----------------------------------------
dy61duv6
Assembly Version: 11.0.0.0
Win32 Version: 2.0.50727.9147 (WinRelRS6.050727-9100)
CodeBase: file:///C:/Windows/assembly/GAC_MSIL/System/2.0.0.0__b77a5c561934e089/System.dll
----------------------------------------
************** JIT Debugging **************
To enable just-in-time (JIT) debugging, the .config file for this
application or computer (machine.config) must have the
jitDebugging value set in the system.windows.forms section.
The application must also be compiled with debugging
enabled.
For example:
<configuration>
<system.windows.forms jitDebugging="true" />
</configuration>
When JIT debugging is enabled, any unhandled exception
will be sent to the JIT debugger registered on the computer
rather than be handled by this dialog box.
現在,我沒有任何程序員技能。 請給我一個簡單明了的答案,並且易於復制以修復此錯誤。
先感謝您。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.