0

I'm not too familiar with signalr2 on asp.net-core pardon me, am trying to create a POC on how to implement a real-time CRUD application with admin and client using signalr2, but am having issues with signalr data push, I keep getting NullReferenceException: Object reference not set to an instance of an object. on this line await Clients.All.SendAsync("BroadcastData", data);

Below is how I setup my Hub using some online examples I looked-up:

public class OddPublisher : Hub
    {

        private readonly IOddServices _oddService;

        public OddPublisher(IOddServices oddService)
        {
            _oddService = oddService;
        }

        public async Task BroadcastData()
        {
            var data = _oddService.ClientQueryOdds();
            await Clients.All.SendAsync("BroadcastData", data); //breaks here
        }

    }

and this is triggered by admin, on submiting and saving the data sucessfully I call the BroadcastData()

    public class BaseController : Controller
    {
        public IOddServices _oddService;
        public readonly OddPublisher _publisher;
        public BaseController(IOddServices oddService, )
        {
            _oddService = oddService;
            _teamService = teamService;

            _publisher = new OddPublisher(oddService);
        }


        [HttpPost]
        public async Task<IActionResult> odd_entry(CreateOdd dto)
        {
            //somecode here...

            var results = _validator.Validate(dto);

            if(!results.IsValid)
            {
                results.AddToModelState(ModelState, null);

                return View(dto);
            }

            _oddService.CreateOddAndTeam(dto);

            await _publisher.BroadcastData(); //Breaks

            return RedirectToAction(nameof(index));
        }
    }

Folled all the instructions as adviced in Microsoft Asp.Net Core Signalr Documentation, my Startup has all required sevices added.

here is the client and the JS file,

"use strict";

var connection = new signalR.HubConnectionBuilder().withUrl("/oddPublisher").build();

connection.on("BroadcastData", data => {

    console.table(data);
    //getAll();
})


connection.start().then(function () {
    getAll();
}).catch(function (err) {
    return console.error(err.toString());
});


function getAll() {
    var model = $('#dataModel');
    $.ajax({
        url: '/home/GetLatestOddData',
        contentType: 'application/html ; charset:utf-8',
        type: 'GET',
        dataType: 'html',
        success: function (result) { model.empty().append(result); }
    });
}

Need some help here guys, I still don't know what am doing wrong, I'll really appreciate if I can get any help on this.

Thank you in advance.

Andy Mike
  • 65
  • 1
  • 2
  • 12

1 Answers1

0

It turns out I needed to Inject the IHubContext into my hubs to have access to the clients.

Andy Mike
  • 65
  • 1
  • 2
  • 12