.Net Core 2.1 - Не удается получить доступ к удаленному объекту. Название объекта: 'IServiceProvider' - программирование
Подтвердить что ты не робот

.Net Core 2.1 - Не удается получить доступ к удаленному объекту. Название объекта: '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(); к моему запуску, но это, похоже, не работает. Все еще получаю ошибку.

EDIT 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
4b9b3361

Ответ 1

Я бы предположил, что вместо вызова services.GetService< IHttpContextAccessor>(), введите IHttpContextAccessor в конструктор и используйте поле aprivate для сохранения значения.

public AppContractResolver(IServiceProvider services, 
                             IHttpContextAccessor  httpContextAccessor )
{
   _services = services;
   this.httpContextAccessor =httpContextAccessor ;
}

Также HttpContextAccessor должен быть зарегистрирован вручную. В RegisterServices в Startup.cs add, services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

Ответ 2

В моем случае проблема была в 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
}

Надеюсь, поможет

Ответ 3

Для меня это работает с:

 public void ConfigureServices(IServiceCollection services)
{
  …
  services.AddHttpContextAccessor();
  …
}

а потом:

     public void Configure(IApplicationBuilder app, IHttpContextAccessor accessor)
    {
    ...
    ...accessor.HttpContext.RequestService

     ...

    }

Ответ 4

Если вы создаете какую-либо временную службу, например services.AddTransient..., ядро .net будет располагать поставщиком услуг. Это ошибка с .net core 2.2.

Ответ 5

Я бы предположил, что реализация IServiceProvider возможно, использовалась в операторе using случайно где-то или была удалена прямо.

Чтобы проверить, если это так, вы можете попытаться разрешить IHttpContextAccessor сразу после или в методе ConfigureServices.

Если он разрешится, вам нужно будет пройти, чтобы узнать, где находится IServiceProvider.

Ответ 6

У меня похожая проблема с приложением (esims), написанным в .Net, и программисты сказали, что ему нужен .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.

Теперь у меня нет навыков программирования. Пожалуйста, дайте мне прямой ответ и легко скопировать для исправления этой ошибки.

Заранее спасибо.