简单的注射器(3.1.5)& SignalR(2.2):SimpleInjector.ActivationException

时间:2016-06-20 11:39:25

标签: c# signalr simple-injector

我尝试实施here提议的集成。不幸的是我的中心方法没有调用。这个例外阻止了它:

  

发生了SimpleInjector.ActivationException。的HResult = -2146233088
  消息=无法访问已处置的对象。 Objektname:   " SimpleInjector.Scope&#34 ;. Source = SimpleInjector StackTrace:          bei SimpleInjector.InstanceProducer.GetInstance()InnerException:          的HResult = -2146232798          消息=无法访问已处置的对象。 Objektname:" SimpleInjector.Scope"。          对象名= SimpleInjector.Scope          来源= SimpleInjector          堆栈跟踪:               bei SimpleInjector.Scope.ThrowObjectDisposedException()               bei SimpleInjector.Scope.RequiresInstanceNotDisposed()               bei SimpleInjector.Scope.GetInstance [TService,TImplementation](ScopedRegistration2   注册)               bei SimpleInjector.Scope.GetInstance [TService,TImplementation](ScopedRegistration2   注册,范围范围)               bei SimpleInjector.Advanced.Internal.LazyScopedRegistration2.GetInstance(范围)   范围)               bei lambda_method(关闭)               bei Glimpse.SimpleInjector.SimpleInjectorTab.CollectResolvedInstance(InitializationContext   context,Func1 instanceProducer)               bei SimpleInjector.Container。<> c__DisplayClass52_0.b__0()               bei SimpleInjector.InstanceProducer.GetInstance()          的InnerException:

这个被抛出:

  

SimpleInjector.dll!SimpleInjector.InstanceProducer.GetInstance()Unbekannt       SimpleInjector.dll!SimpleInjector.Container.GetInstance(System.Type serviceType)Unbekannt     idee5.Dispatcher.dll!SimpleInjector.SignalR.SimpleInjectorHubActivator.Create(Microsoft.AspNet.SignalR.Hubs.HubDescriptor描述符)Zeile 11 C#       Microsoft.AspNet.SignalR.Core.dll!Microsoft.AspNet.SignalR.Hubs.DefaultHubManager.ResolveHub(string hubName)Unbekannt       Microsoft.AspNet.SignalR.Core.dll!Microsoft.AspNet.SignalR.Hubs.HubDispatcher.CreateHub(Microsoft.AspNet.SignalR.IRequest请求,Microsoft.AspNet.SignalR.Hubs.HubDescriptor描述符,字符串connectionId,Microsoft.AspNet.SignalR .Hubs.StateChangeTracker跟踪器,bool throwIfFailedToCreate)Unbekannt       Microsoft.AspNet.SignalR.Core.dll!Microsoft.AspNet.SignalR.Hubs.HubDispatcher.OnReceived(Microsoft.AspNet.SignalR.IRequest请求,字符串connectionId,字符串数据)Unbekannt       Microsoft.AspNet.SignalR.Core.dll!Microsoft.AspNet.SignalR.PersistentConnection.ProcessRequestPostGroupRead.AnonymousMethod__7()Unbekannt       Microsoft.AspNet.SignalR.Core.dll!Microsoft.AspNet.SignalR.TaskAsyncHelper.FromMethod(System.Func func)Unbekannt       Microsoft.AspNet.SignalR.Core.dll!Microsoft.AspNet.SignalR.PersistentConnection.ProcessRequestPostGroupRead.AnonymousMethod__6(字符串数据)Unbekannt       Microsoft.AspNet.SignalR.Core.dll!Microsoft.AspNet.SignalR.Transports.WebSocketTransport.OnMessage(string message)Unbekannt       Microsoft.AspNet.SignalR.Core.dll!Microsoft.AspNet.SignalR.WebSockets.DefaultWebSocketHandler.OnMessage(string message)Unbekannt       Microsoft.AspNet.SignalR.Core.dll!Microsoft.AspNet.SignalR.WebSockets.WebSocketHandler.ProcessWebSocketRequestAsync(System.Net.WebSockets.WebSocket webSocket,System.Threading.CancellationToken disconnectToken,System.Func> messageRetriever,object state)Unbekannt       mscorlib.dll!System.Runtime.CompilerServices.AsyncMethodBuilderCore.MoveNextRunner.InvokeMoveNext(object stateMachine)Unbekannt       mscorlib.dll!System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext executionContext,System.Threading.ContextCallback callback,object state,bool preserveSyncCtx)Unbekannt       mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext,System.Threading.ContextCallback callback,object state,bool preserveSyncCtx)Unbekannt       mscorlib.dll!System.Runtime.CompilerServices.AsyncMethodBuilderCore.MoveNextRunner.Run()Unbekannt       mscorlib.dll!System.Runtime.CompilerServices.AsyncMethodBuilderCore.OutputAsyncCausalityEvents.AnonymousMethod__0()Unbekannt       mscorlib.dll!System.Runtime.CompilerServices.AsyncMethodBuilderCore.ContinuationWrapper.Invoke()Unbekannt       mscorlib.dll!System.Runtime.CompilerServices.TaskAwaiter.OutputWaitEtwEvents.AnonymousMethod__0()Unbekannt       mscorlib.dll!System.Runtime.CompilerServices.AsyncMethodBuilderCore.ContinuationWrapper.Invoke()Unbekannt       mscorlib.dll!System.Threading.Tasks.SynchronizationContextAwaitTaskContinuation..cctor.AnonymousMethod__8_0(对象状态)Unbekannt       System.Web.dll!System.Web.AspNetSynchronizationContext.Post.AnonymousMethod__0()Unbekannt       System.Web.dll!System.Web.Util.SynchronizationHelper.SafeWrapCallback(System.Action action)Unbekannt       System.Web.dll!System.Web.Util.SynchronizationHelper.QueueAsynchronous.AnonymousMethod__0(System.Threading.Tasks.Task _)Unbekannt       mscorlib.dll!System.Threading.Tasks.ContinuationTaskFromTask.InnerInvoke()Unbekannt       mscorlib.dll!System.Threading.Tasks.Task.Execute()Unbekannt       mscorlib.dll!System.Threading.Tasks.Task.ExecutionContextCallback(object obj)Unbekannt       mscorlib.dll!System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext executionContext,System.Threading.ContextCallback callback,object state,bool preserveSyncCtx)Unbekannt       mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext,System.Threading.ContextCallback callback,object state,bool preserveSyncCtx)Unbekannt       mscorlib.dll!System.Threading.Tasks.Task.ExecuteWithThreadLocal(ref System.Threading.Tasks.Task currentTaskSlot)Unbekannt       mscorlib.dll!System.Threading.Tasks.Task.ExecuteEntry(bool bPreventDoubleExecution)Unbekannt       mscorlib.dll!System.Threading.Tasks.Task.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()Unbekannt       mscorlib.dll!System.Threading.ThreadPoolWorkQueue.Dispatch()Unbekannt       mscorlib.dll!System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()

另一个可疑的例外是:

  

SimpleInjector.ActivationException ist aufgetreten。     的HResult = -2146233088     Message = SchedulerHub注册为'混合执行上下文范围/ Web请求'生活方式,但实例是在混合执行上下文范围/ Web请求的上下文之外请求的。     来源= SimpleInjector     堆栈跟踪:          bei SimpleInjector.Scope.GetScopelessInstance [TService,TImplementation](ScopedRegistration`2 registration)     InnerException:

这个被抛出:

  

SimpleInjector.dll!SimpleInjector.Scope.GetScopelessInstance(SimpleInjector.Lifestyles.ScopedRegistration registration)Unbekannt       SimpleInjector.dll!SimpleInjector.Scope.GetInstance(SimpleInjector.Lifestyles.ScopedRegistration注册,SimpleInjector.Scope范围)Unbekannt       SimpleInjector.dll!SimpleInjector.Advanced.Internal.LazyScopedRegistration.GetInstance(SimpleInjector.Scope scope)Unbekannt       [Lightweightfunktion]
      Glimpse.SimpleInjector.dll!Glimpse.SimpleInjector.SimpleInjectorTab.CollectResolvedInstance(SimpleInjector.Advanced.InitializationContext context,System.Func instanceProducer)Unbekannt       SimpleInjector.dll!SimpleInjector.Container.ApplyResolveInterceptor.AnonymousMethod__0()Unbekannt       SimpleInjector.dll!SimpleInjector.InstanceProducer.GetInstance()Unbekannt       SimpleInjector.dll!SimpleInjector.Container.GetInstance(System.Type serviceType)Unbekannt     idee5.Dispatcher.dll!SimpleInjector.SignalR.SimpleInjectorHubActivator.Create(Microsoft.AspNet.SignalR.Hubs.HubDescriptor描述符)Zeile 11 C#       Microsoft.AspNet.SignalR.Core.dll!Microsoft.AspNet.SignalR.Hubs.DefaultHubManager.ResolveHub(string hubName)Unbekannt       Microsoft.AspNet.SignalR.Core.dll!Microsoft.AspNet.SignalR.Hubs.HubDispatcher.CreateHub(Microsoft.AspNet.SignalR.IRequest请求,Microsoft.AspNet.SignalR.Hubs.HubDescriptor描述符,字符串connectionId,Microsoft.AspNet.SignalR .Hubs.StateChangeTracker跟踪器,bool throwIfFailedToCreate)Unbekannt       Microsoft.AspNet.SignalR.Core.dll!Microsoft.AspNet.SignalR.Hubs.HubDispatcher.GetHubs.AnonymousMethod__39(Microsoft.AspNet.SignalR.Hubs.HubDescriptor descriptor)Unbekannt       System.Core.dll!System.Linq.Enumerable.WhereSelectListIterator.MoveNext()Unbekannt       System.Core.dll!System.Linq.Enumerable.WhereEnumerableIterator.MoveNext()Unbekannt       mscorlib.dll!System.Collections.Generic.List.List(System.Collections.Generic.IEnumerable collection)Unbekannt       System.Core.dll!System.Linq.Enumerable.ToList(System.Collections.Generic.IEnumerable source)Unbekannt       Microsoft.AspNet.SignalR.Core.dll!Microsoft.AspNet.SignalR.Hubs.HubDispatcher.ExecuteHubEvent(Microsoft.AspNet.SignalR.IRequest request,string connectionId,System.Func action)Unbekannt       Microsoft.AspNet.SignalR.Core.dll!Microsoft.AspNet.SignalR.Hubs.HubDispatcher.OnReconnected(Microsoft.AspNet.SignalR.IRequest request,string connectionId)Unbekannt       Microsoft.AspNet.SignalR.Core.dll!Microsoft.AspNet.SignalR.PersistentConnection.ProcessRequestPostGroupRead.AnonymousMethod__5()Unbekannt       Microsoft.AspNet.SignalR.Core.dll!Microsoft.AspNet.SignalR.TaskAsyncHelper.FromMethod(System.Func func)Unbekannt       Microsoft.AspNet.SignalR.Core.dll!Microsoft.AspNet.SignalR.PersistentConnection.ProcessRequestPostGroupRead.AnonymousMethod__4()Unbekannt       Microsoft.AspNet.SignalR.Core.dll!Microsoft.AspNet.SignalR.Transports.ForeverTransport.ProcessReceiveRequest.AnonymousMethod__1c()Unbekannt       Microsoft.AspNet.SignalR.Core.dll!Microsoft.AspNet.SignalR.Transports.ForeverTransport.ProcessMessages(Microsoft.AspNet.SignalR.Transports.ITransportConnection connection,System.Func initialize)Unbekannt       Microsoft.AspNet.SignalR.Core.dll!Microsoft.AspNet.SignalR.Transports.ForeverTransport.ProcessReceiveRequest(Microsoft.AspNet.SignalR.Transports.ITransportConnection connection)Unbekannt       Microsoft.AspNet.SignalR.Core.dll!Microsoft.AspNet.SignalR.Transports.ForeverTransport.ProcessRequestCore.AnonymousMethod__e(Microsoft.AspNet.SignalR.Transports.ForeverTransport t,Microsoft.AspNet.SignalR.Transports.ITransportConnection c)Unbekannt       Microsoft.AspNet.SignalR.Core.dll!Microsoft.AspNet.SignalR.TaskAsyncHelper.FromMethod(System.Func func,System .__ Canon arg1,System .__ Canon arg2)Unbekannt       Microsoft.AspNet.SignalR.Core.dll!Microsoft.AspNet.SignalR.TaskAsyncHelper.Then(System.Threading.Tasks.Task任务,System.Func后继者,Microsoft.AspNet.SignalR.Transports.ForeverTransport arg1,Microsoft.AspNet.SignalR .Transports.ITransportConnection arg2)Unbekannt       Microsoft.AspNet.SignalR.Core.dll!Microsoft.AspNet.SignalR.Transports.ForeverTransport.ProcessRequestCore(Microsoft.AspNet.SignalR.Transports.ITransportConnection connection)Unbekannt       Microsoft.AspNet.SignalR.Core.dll!Microsoft.AspNet.SignalR.Transports.WebSocketTransport.ProcessRequest.AnonymousMethod__2(Microsoft.AspNet.SignalR.Hosting.IWebSocket socket)Unbekannt       Microsoft.AspNet.SignalR.Core.dll!Microsoft.AspNet.SignalR.Owin.OwinWebSocketHandler.RunWebSocketHandler.AnonymousMethod__0()Unbekannt       mscorlib.dll!System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Startc__DisplayClass1。< b__0> d__3 stateMachine)Unbekannt       Microsoft.AspNet.SignalR.Core.dll!Microsoft.AspNet.SignalR.Owin.OwinWebSocketHandler.RunWebSocketHandler.AnonymousMethod__0()Unbekannt       mscorlib.dll!System.Threading.Tasks.Task.InnerInvoke()Unbekannt       mscorlib.dll!System.Threading.Tasks.Task.Execute()Unbekannt       mscorlib.dll!System.Threading.Tasks.Task.ExecutionContextCallback(object obj)Unbekannt       mscorlib.dll!System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext executionContext,System.Threading.ContextCallback callback,object state,bool preserveSyncCtx)Unbekannt       mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext,System.Threading.ContextCallback callback,object state,bool preserveSyncCtx)Unbekannt       mscorlib.dll!System.Threading.Tasks.Task.ExecuteWithThreadLocal(ref System.Threading.Tasks.Task currentTaskSlot)Unbekannt       mscorlib.dll!System.Threading.Tasks.Task.ExecuteEntry(bool bPreventDoubleExecution)Unbekannt       mscorlib.dll!System.Threading.Tasks.Task.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()Unbekannt       mscorlib.dll!System.Threading.ThreadPoolWorkQueue.Dispatch()Unbekannt       mscorlib.dll!System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()Unbekannt

两者都被抓住了。而且我怀疑这似乎没有发生任何事情,我的集线器方法也没有被调用。

经过一些尝试错误的会话后,我最终得到了这个容器配置。

    public static Container GetInitializeContainer(IAppBuilder app) {
    // configure AutoMapper
    MapperConfiguration mapperConfig = ConfigureMappings();

    // Create the container as usual.
    var container = new Container();
    ScopedLifestyle hybrid = Lifestyle.CreateHybrid(
        () => container.GetCurrentExecutionContextScope() != null,
        new ExecutionContextScopeLifestyle(),
        new WebRequestLifestyle());
    container.Options.DefaultScopedLifestyle = hybrid;

    // Registering the types
    container.RegisterSingleton(() => mapperConfig.CreateMapper());
    container.RegisterSingleton(app);
    container.RegisterPerWebRequest<IUrlHelperProvider, UrlHelperProvider>();
    // register the singleton services
    container.RegisterSingleton<ICacheService>(new CacheService());
    container.RegisterSingleton<ILoggingService, LoggingService>();

    // register application services
    // get the assembly containing the services 
    Assembly repositoryAssembly = typeof(CompanyService).Assembly;
    // get the services namespace
    string @namespace = typeof(CompanyService).Namespace;
    // register all interfaces in the assembly besides the singletons
    var registrations =
        from type in repositoryAssembly.GetExportedTypes()
        where type.Namespace == @namespace
        where type.GetInterfaces().Any(i => i.Name.EndsWith(value: "Service") &&
            i.Name != nameof(ICacheService) && i.Name != nameof(ILoggingService))
        select new { Service = type.GetInterfaces().Single(i => i.Name.EndsWith(value: "Service")), Implementation = type };

    foreach (var reg in registrations) {
        container.Register(reg.Service, reg.Implementation, new WebRequestLifestyle());
    }

    container.RegisterPerWebRequest<ApplicationUserManager>();
    container.RegisterPerWebRequest<IUserStore<IdentityUser, Guid>>(() => new UserStore());
    container.RegisterInitializer<ApplicationUserManager>(manager => InitializeUserManager(manager, app));
    // register the role manager
    container.RegisterPerWebRequest<ApplicationRoleManager>();
    container.RegisterPerWebRequest<IRoleStore<IdentityRole, Guid>>(() => new RoleStore());
    container.RegisterInitializer<ApplicationRoleManager>(manager => InitializeRoleManager(manager));

    container.Register<Hubs.SchedulerHub, Hubs.SchedulerHub>(Lifestyle.Scoped);
    // register the sign in manager
    container.RegisterPerWebRequest<ApplicationSignInManager>();
    container.RegisterPerWebRequest(() => AdvancedExtensions.IsVerifying(container)
            ? new OwinContext(new Dictionary<string, object>()).Authentication
            : HttpContext.Current.GetOwinContext().Authentication);

    // Register all controllers and filters. Including those in MVC areas
    container.RegisterMvcControllers();
    container.RegisterMvcIntegratedFilterProvider();

    // register OWIN
    app.Use(async (context, next) => {
        using (container.BeginExecutionContextScope()) {
            CallContext.LogicalSetData(name: "IOwinContext", data: context);
            await next();
        }
    });
    container.RegisterSingleton<IOwinContextProvider>(new CallContextOwinContextProvider());

    return container;
}

我的中心激活器:

    public class SimpleInjectorHubActivator : IHubActivator {
    public SimpleInjectorHubActivator(Container container) {
        _container = container;
    }

    public IHub Create(HubDescriptor descriptor) {
        return (IHub) _container.GetInstance(descriptor.HubType);
    }

    private readonly Container _container;
}

我的枢纽调度员:

public class SimpleInjectorHubDispatcher : HubDispatcher {
    public SimpleInjectorHubDispatcher(Container container, HubConfiguration configuration)
        : base(configuration) {
        _container = container;
    }

    protected override Task OnConnected(IRequest request, string connectionId) {
        return Invoke(() => base.OnConnected(request, connectionId));
    }

    protected override Task OnReceived(IRequest request, string connectionId, string data) {
        return Invoke(() => base.OnReceived(request, connectionId, data));
    }

    protected override Task OnDisconnected(IRequest request, string connectionId,
        bool stopCalled) {
        return Invoke(() => base.OnDisconnected(request, connectionId, stopCalled));
    }

    protected override Task OnReconnected(IRequest request, string connectionId) {
        return Invoke(() => base.OnReconnected(request, connectionId));
    }

    private async Task Invoke(Func<Task> method) {
        using (_container.BeginExecutionContextScope())
            await method();
    }

    private readonly Container _container;
}

如何防止此异常并调用我的集线器方法?

2 个答案:

答案 0 :(得分:2)

从堆栈跟踪中我看到默认HubDispatcher被调用,而不是您的自定义SimpleInjectorHubDispatcher。这意味着不应用范围,这可能是您收到消息“在混合执行上下文范围/ Web请求的上下文之外请求实例”的原因。

您应该注册SimpleInjectorHubDispatcher,如下所示: 我认为错误在以下几行:

var dispatcher = new SimpleInjectorHubDispatcher(container, config);
config.Resolver.Register(typeof(HubDispatcher), dispatcher);

答案 1 :(得分:1)

感谢史蒂文斯的聊天支持和一些深挖,我发现了这个漏洞。我混淆了集线器的生活方式和使用过的服务。

困难的部分是收集有关静默失败的SignalR呼叫的任何细节。如果有其他人遇到这种情况,我想就如何收集更多信息分享两个提示:

  • 仔细查看调试输出并查找可疑异常。
  • 如果发生这种情况,请告诉Visual Studio中断。

这样你就可以掌握堆栈跟踪,内部异常等。否则你不会找到原因。 在我的情况下,我监控了SimpleInjector.ActivationException,Steven帮我找到了原因。