2

I try to send the received data from a webservice call to my javascript clients. What is the correct approach? Should I create a hubContext in the Controller class

//Controller 
var data = this.getData(_Ids);
var hubContext = GlobalHost.ConnectionManager.GetHubContext<Hubs.MyHub>();
hubContext.Clients.Client(cc.ConnectionId).receiveData(data);

and send the received data this way. Or should I create a controller in the Hub class to get the data there and send it in the Hub

//SignalR Hub
var data = new MyController().getData(_Ids);
Clients.Client(cpm.ConnectionId).receiveData(data);

1 Answer 1

0

You should never instantiate a Controller detached from the current execution context with the small exception being mocking as a part of unit testing.

Constructs like:

var data = new MyController().getData(_Ids);

Best be avoided. If deciding from the two its better to fetch the hub context from the controller.

Your example however is incomplete as you dont show whats inside of the getData(_Ids) method, you say you fetch the data from a web service?

Perhaps you can encapsulate the retrieval logic i.e getData(_Ids) in receiveData() within the Hub itself, or if you're calling this service in more places you could also define a static adapter helper class which will wrap around the calls to the web service and this adapter could later be used within receiveData() method of the hub.

Note that depending on the application your writing, its scope and functionality it might be a good idea to use some Dependency Injection framework like Autofac or Ninject and just inject IConnectionManager into the Controller through the constructor instead of instantiating it in the methods.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your answer. I tried the static adapter helper but in this case i had a problem with my authentication token. So i use the first approach.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.