dotnet / AspNetCore.Docs

Documentation for ASP.NET Core
https://docs.microsoft.com/aspnet/core
Creative Commons Attribution 4.0 International
12.57k stars 25.3k forks source link

Using DI in Hubs #9676

Closed hrnsky closed 5 years ago

hrnsky commented 5 years ago

Hello, I want to use a singleton service inside Hubs, I couldn't inject it like this public class ExampleHub : Hub { private readonly Myclass _myclass; public ExampleHub(Myclass myclass) { _myclass = myclass; } } It throws "System.ObjectDisposedException: Cannot access a disposed object."

Also I cannot inject the class like this public class ExampleHub : Hub { public async void SomeMethod(string parameter1, [FromServices] Myclass myclass) { } } It throws "System.IO.InvalidDataException: Invocation provides 2 argument(s) but target expects 1." How possible is this ? Thanks. I'm using Asp.Net Core 2.1

Rick-Anderson commented 5 years ago

Thanks for the question. You'll probably get a faster answer on a support forum, such as Stack Overflow, or a support chat, such as Slack or Gitter. If you post the question elsewhere, please update this issue with the link.

Rick-Anderson commented 5 years ago

Would you mind opening this issues with the "content feedback" button at the bottom of the page? It helps us keep track of issues related to docs and gets the attention of the doc owners.

Also, what's the scenario for doing this?

hrnsky commented 5 years ago

Thanks for response, I tried to google it but found nothing to use DI in signalr, also there is not much document about asp.net core, I have a class that connects a realtime api and saves it to db or sends to the client but for both situation I need to send an "OK" response to the client, I'm using this class in controllers, hostedservices and middleware, but couldn't inject to signalr, tried to inject with usual way but throws these exceptions. There is another opened issue about it, Maybe it's the same issue, I don't know. I can track the issue #9658. Feel free to close, or delete, I will open a feedback in document page.