English 中文(简体)
试图激活 XXXXX 时无法解析 Microsoft.AspNetCore.SignalR.Hub`1[IXXXX] 类型服务
原标题:Unable to resolve service for type Microsoft.AspNetCore.SignalR.Hub`1[IXXXX] while attempting to activate XXXXX
I define my strong typed SignalR hub exactly by MS Rules public class OutputMessages : Hub {...} than inject my SignalR hub to conctoller by the same way public class ApplicationAPIController : ControllerBase { public ApplicationAPIController(IHubContext _outputMessages) {...} } In Startup I add SignalR service as services.AddSignalR() .AddHubOptions(options => { options.EnableDetailedErrors = true; }) and define endpoint app.UseEndpoints(endpoints => { endpoints.MapHub("/OutputMessages", options => { options.Transports = HttpTransportType.WebSockets | HttpTransportType.LongPolling; }); }); Looks good? Yes. And compilation is good. But in runTime I receive fail: Microsoft.AspNetCore.SignalR.HubConnectionHandler[1] Error when dispatching OnConnectedAsync on hub. System.InvalidOperationException: Unable to resolve service for type Microsoft.AspNetCore.SignalR.Hub`1[IOutputMessages] while attempting to activate OutputMessages . at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, Boolean isDefaultParameterRequired) at lambda_method(Closure , IServiceProvider , Object[] ) at Microsoft.AspNetCore.SignalR.Internal.DefaultHubActivator`1.Create() at Microsoft.AspNetCore.SignalR.Internal.DefaultHubDispatcher`1.OnConnectedAsync(HubConnectionContext connection) at Microsoft.AspNetCore.SignalR.Internal.DefaultHubDispatcher`1.OnConnectedAsync(HubConnectionContext connection) at Microsoft.AspNetCore.SignalR.HubConnectionHandler`1.RunHubAsync(HubConnectionContext connection) dbug: Microsoft.AspNetCore.SignalR.HubConnectionHandler[6] OnConnectedAsync ending.
问题回答
and finally I found a solution this is my strong type Hub definition public class OutputMessages : Hub { public static readonly Dictionary ConnectedUserList = new Dictionary(1024); private readonly IHubContext _hubContext; private readonly ApplicationDbContext _db; private readonly ILogger _logger; public OutputMessages(IHubContext hubContext, ILogger logger, ApplicationDbContext dbContext) { _hubContext = hubContext; _db = dbContext; _logger = logger; } .... public async Task AdminMessages2(string userId, string message, bool consoleOnly) { string uname = await Username(userId); await _hubContext.Clients.All.AdminMessages2(userId, "API: " + uname + " " + message, consoleOnly); } [ResponseCache(VaryByHeader = "id", Duration = 36000, Location = ResponseCacheLocation.Any)] public async Task Username(string id) { ApplicationUser user = null; await Task.Run(() => user = _db.Users.Find(id)); return user.UserName; } public override async Task OnConnectedAsync() { string JWT = Context.GetHttpContext().Request.Headers["Authorization"]; string ValidUserID = UserHelpers.ValidateJWT(JWT); if (ValidUserID != null) { _logger.LogInformation($"User {ValidUserID} connected to {this.GetType().Name} hub"); if (ConnectedUserList.Any(x => x.Key == ValidUserID)) { ConnectedUserList.Remove(ValidUserID); } ConnectedUserList.Add(ValidUserID, Context.ConnectionId); } await base.OnConnectedAsync(); } public override async Task OnDisconnectedAsync(System.Exception exception) { var JWT = Context.GetHttpContext().Request.Headers["Authorization"]; string ValidUserID = UserHelpers.ValidateJWT(JWT); if (ValidUserID != null) { _logger.LogInformation($"User {ValidUserID} disconnected from {this.GetType().Name} hub"); if (ConnectedUserList.Any(x => x.Key == ValidUserID)) { ConnectedUserList.Remove(ValidUserID); } ConnectedUserList.Add(ValidUserID, Context.ConnectionId); } await base.OnDisconnectedAsync(exception); } } and this is injection Hub to controller public class ApplicationAPIController : ControllerBase { public ApplicationAPIController(ILogger logger, ApplicationDbContext dbContext, IConfiguration Configuration, CoreObjectDumper.CoreObjectDumper dump, IHubContext _outputMessages) { ... definition of SignalR service in StartUp not changed. Problem is create Hub from class instead interface and Hub constructor must be exactly IHubContext
In my case, I was using the ABP framework when this error occurred and I found that ABP (partially) removed the implementation of the class that lacked the DI, IOnlineClientManager See: https://github.com/aspnetboilerplate/aspnetboilerplate/commit/30b70e9a7f4395a2103219cdfd4b9499d35ebf3b The solution was then to remove the generic implementations of those classes ( and everywhere where they are being refferred) IOnlineClientManager onlineClientManager, here removing ChatChannel solved it for me.




相关问题
How to Inject Open Connections with an IoC

First, my scenario. I have a service, BillingService, has a constructor like this: BillingService(IInstallmentService, IBillingRepository) The InstallmentService has a constructor that looks like ...

Using the Ninject kernel as a Unit of Work object factory

So I m starting to use Ninject for dependency injection and I m wondering what people think of using a kernel as an object factory for Unit of Work type objects like Linq2Sql Datacontexts. I would ...

array dependency injection in spring?

is there a way to use dependency injection to inject all available implementations of a specific interface in spring? This is kind of the same thing as asked here for .NET. Though my aim is to use @...

Unity constructors

I have setup unity in my project and it is working for objects that don t have constructor injection implemented on them. The issue is now I do have an object which requires a custom object as a ...

Grails Packaging and Naming Conventions

Packaging Controllers, Services,etc. i.e. - com.company.controllers - com.company.services Is this a good practice or should be avoided by all means?? Another worth mentioning problem I encountered ...

ASP.NET MVP Injecting Service Dependency

I have an ASP.NET page that implements my view and creates the presenter in the page constuctor. Phil Haack s post providing was used as the starting point, and I ll just the examples from the post ...

Authorization and Windsor

I m trying to implement my custom authorize attribute like: public class MyCustomAuth : AuthorizeAttribute { private readonly IUserService _userService; public MyCustomAuth(IUserService ...

热门标签