Thursday, 18 December 2014

Getting NServiceBus, SignalR and Autofac to work together

I’m currently working on an existing web app that we’re updating to add in NServiceBus and SignalR. A broad brush overview is shown below…


Here a request is sent from the browser which goes to a SignalR hub inside the website. That request is then sent onto the bus and some back end magic happens, which ultimately ends up in a response being sent to the bus. This is picked up by the website and a response is pushed down to the client courtesy of SignalR.

If we look into what’s happening inside the website we see the following…


The hub implements an interface that’s injected into the message handler, so that the handler can call back to the hub when the response message comes in, which ultimately then makes the hub call back to the browser to finish the loop.

Getting all this setup was a bit of a bother and I went down a few blind alleys before getting it all to work properly, hence documenting it so that I can hopefully short-circuit someone else’s work.

In pseudocode this is what happens…

  • The browser makes a request to the hub.
  • The hub code creates a unique Request Id, and stuffs this into a dictionary, mapping this Request Id to the SignalR Context.ConnectionId.
  • The hub then sends a message onto the bus, this contains the Request Id.
  • After the back-end has processed this message a response is placed on the bus, again containing the Request Id.
  • The message handler receives the message and uses the callback interface and Request Id to build a dynamic object that we can call the browser back with.
  • The message handler then makes the callback.

For this example I’m doing the callback within the message handler, but you could encapsulate this fully within the Hub too if you prefer. OK, enough explanation, on to some code…

    public interface ICallback
dynamic GetCallback(Guid requestId);

This interface is used to communicate between the message handler and the Hub. In addition I added a “registration” service that is used to map a Request Id to a client connection Id…

    public interface IRegistration
void Register(Guid id, string data);

string GetRegistration(Guid id);

The implementation of this service was a simple dictionary, this however should be beefed up as it needs a “tidy up” mechanism that will ensure that data is removed from this dictionary when the client disappears. The hub then is as shown below…

    public class WibbleHub : Hub, ICallback
public WibbleHub(IBus bus, IRegistration registration)
_bus = bus;
_reg = registration;

public void RequestWibble(string text)
Guid requestId = Guid.NewGuid();

_reg.Register(requestId, Context.ConnectionId);

_bus.Send(new WibbleMessage { RequestId = requestId, Text = text});

public dynamic GetCallback(Guid requestId)
dynamic callback = null;
string clientId = _reg.GetRegistration(requestId);

if (null != clientId)
callback = Clients.Client(clientId);

return callback;

private IBus _bus;
private IRegistration _reg;

The hub imports the bus and registration services, and the RequestWibble method is the one we’re calling from the web client. This registers the mapping between the Request Id and the client Connection Id, and then sends a message onto the bus.

The GetCallback method uses the registration service to find the client connection Id, then returns a dynamic object hooked to that client if the Id matches one that has been registered.

The message handler is fairly simple too…

    public class WibbleHandler : IHandleMessages<WibbleMessage>
public WibbleHandler(ICallback callback)
_callback = callback;

public void Handle(WibbleMessage message)
var cb = _callback.GetCallback(message.RequestId);

if (null != cb)
catch (Exception ex)
int i = 0;

private ICallback _callback;

The handler imports the ICallback interface (exposed by the Hub), and when it handles the incoming message it calls the GetCallback() method to retrieve the dynamic object that allows us to call down to the web client.

The last piece of the puzzle is wiring this up, and that was the main thing that took time to get right, mainly down to my misunderstanding of how NServiceBus does its stuff. I created a DependenciesConfig file as follows…

    public static class DependencyConfig
public static void BuildDependencies()
var container = BuildContainer();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

public static IContainer BuildContainer()
if (null == _container)
var builder = new ContainerBuilder();




_container = builder.Build();

var config = new BusConfiguration();
config.UseContainer<AutofacBuilder>(c => c.ExistingLifetimeScope(_container));

var bus = Bus.Create(config);


return _container;

private static IContainer _container;

This has a static BuildContainer method that creates the AutoFac container, and there are a couple of things of note. First off is the registration of the hub, this is registered as a singleton, as is the registration service too.

Then (and this is the bit that I got wrong) is the configuration of the bus. First off, the container is built before the bus is constructed, so the bus itself is not constructed as part of the container itself, it lives “outside”. The bus is setup to hook to the Autofac container using the UseContainer() member, this links the bus to the registered components, and means that when a message comes in on the bus that it can resolve all dependencies such as the ICallback interface exposed by the hub.

Now to the voodoo magic. In the above there is nowhere that the bus itself is registered with the Autofac container, so conventional wisdom would dictate that any components requiring IBus wouldn’t be able to resolve it, so for example this controller shouldn’t work…

    public class DefaultController : Controller
public DefaultController(IBus bus)
_bus = bus;

public ActionResult Index()
return View();

private IBus _bus;

But it does work. How is a mystery. After a bit of searching I came across this post on Stack Overflow that indicates that NSB does this for you. That’s great, but also somewhat confusing for anyone who doesn’t know this beforehand, which presumably is everyone who uses NSB and Autofac, or any IOC container probably as people are used to registering dependencies themselves, rather than some magic happening. Personally I’m not a fan of this magic, it’ll most likely trip you up. However, with this in place it all works as expected – I can then pop some Javascript into my client and everything works as expected.

There’s one more class to add and that’s the startup for Owin, so that we can get SignalR up and running properly…

    public class Startup
public void Configuration(IAppBuilder app)
var container = DependencyConfig.BuildContainer();

GlobalHost.DependencyResolver = new AutofacDependencyResolver(container);
app.MapSignalR(new HubConfiguration { EnableDetailedErrors = true });

The demo (attached) has a simple form where you can enter text, click a button and lo and behold a message is displayed on screen. That’s pretty useless, but at least is shows how NServiceBus, Autofac and SIgnalR can play nicely together. I’m using RabbitMQ as my messaging infrastructure, feel free to bring your own along if you would prefer.

Hope this helps someone!


Anonymous said...

Thanks, this was exactly what i needed to get my hubs being called from my business logic.

rushmyessay discount code said...

So much coding in this post and quite hard to understand the coding part, also explain each block of coding with an explanation. Thanks

Oliver Maurice said...

I recommend that you read this little article about essay writing to get the best information possible about the subject. Good luck

Unknown said...

I would like to say that this article really convinced me, you give me best information!

AngelaHolt said...

Thanks blogger for sharing the best article.Score hero mod Traffic rider mod apk Vector mod

Robert James said...

This is amazing you have defined very well and I got the more benefit from it and the structure and flow of your content with the engaging content is so good I have learnt a lots of things from it. best assignment writers UK appreciate it.

Rebecca Virginia said...

The post is very informative, thank you for sharing the hub and interface topic information.
Assignment Writing in UAE

Puremelda said...

Our nursing essay writing services and college research paper service work collaboratively with our team of researchers to ensure that every order is thoroughly researched before drafting.

meldaresearch said...

We are one of the best custom writing companies as we submit our papers on time and students will have a satisfactory time to go over the essay trying to counter check for any mistake or error which might need urgent correction. Order a custom assignment help and get the best results.

Stefan Carl said...

Students of New Zealand can buy coursework New Zealand help from We provide instant coursework writing help to the students with free revisions and plagiarism free content.

Assignment Help said...

I appreciate the effort you made to share the knowledge. This is really great stuff for sharing. We also provide an assignment to help Australia students.For more info visit:
Operations Research Assignment Help

Angel Claudia said...

Our cheapest essay writing service is not meant to make students lazy, but enable them to submit papers that adhere to the instructors’ guidelines as students seek services for who can offer cheap reliable essay writing services.

KeiraDoltan said...

Most of the student Fear of Missing Deadline. and therefore stress out for any kind of Academic work. If You Hire, Strategic Management Assignment Help Then you will be able to meet Deadline Without any burden.

William Shell said...

Hey, Your blog is very informative. It is nice to read such high-quality content. Attractive information on your blog, thank you for taking the time and share with us. Myassignmenthelp delivers high-quality content related to perfect essay help online UK.

Ethan Lee said...

Are you looking for assignment help in Sydney? Contact me, I will help you. is the home of Australia's best academic writers. Whether you need Assignment help Perth, Assignment Help Brisbane or Assignment Help Adelaide, we can help you.
We will also help you for
Assignment Help Perth,
Assignment Help Brisbane,
Assignment Help Melbourne

daisythomas said...
This comment has been removed by the author.
daisythomas said...

Get My Assignment Help services from at the cheap prices. Our High-Qualified writers work according to Assignment requirement guidelines. 24x7 online customer support team. Get your order and improve your Grades. For more information contact here- or + 44-755-536-9184.

ireland assignment help said...

Get the doctoral dissertation writing assistance by the expert writers at Assignment Help. Our masters have earned their degrees from the renowned universities of Ireland. They are fluent in writing assignments without missing the deadlines.

georgethomas said...

GoAssignmentHelp is very useful for the students who are doing their masters and want to submit the document to take their degree. We are providing the best assignment service to everyone. Just contact us at +61-0283206023 for the best quality services. All subjects and types of assignments available.
Assignment Help Brisbane | my assignment help | programming assignment help

Puremelda said...

Are you searching for the most reliable Already Written Essays? All the Custom Dissertation Writing should be original based on in-depth research and include appropriate citations based on current references on the Pre Written Essays.

Florahmelda said...

Our Creative Essay Writing Service is accessible online via a majority of mobile devices to bring most Affordable Creative Essay Papers close to you. Students can access Online Creative Essay For Sale from any location if they have a pertinent mobile device.

Puremelda said...

A Custom Writing Company should offer legitimate College Research Paper Services, Cheap Custom Research Paper Services and high quality Custom College Paper Services.

michaelgordon said...

Deep learning is a concept that should be implemented everywhere because this is what true learning is and gives students a total understanding of the subject. For assignment help and guidance on a college assignment, visit GoAssignmentHelp for best assignment help in sydney Services​

Online Assignment Help said...

You need to have in-depth knowledge of statistics as well as knowledge of perdisco. Most of the students fail this test. We don’t want them to fail and this is why we started to provide
statistics perdisco help
at affordable prices. We have specialist academic writers in our team who are always ready to help you with your assignments. They assure you of timely delivery and they have a track record of 95% passing marks. You can seek their help whenever you need it and contact the customer support department round the clock. You will get perdisco help at every step of the writing thus improving your knowledge.

Max Willor said...

Very informative and well-written post! Quite an interesting and nice topic chosen for the post. My Assignment Help Au has been a pioneer within the Best Assignment Help Perth on-line services and within Australia and different countries ceaselessly for over Seven years. Make an order now for professional work, delivered on time and pure.

Sam said...

MyAssignmentHelp is the leading online assignment writing service that have been successfully serving the students of Australia. Our extraordinary writing experts cover a wide range of subjects and domains for the students of top-notch colleges and universities, and we have become a most trusted partner in academic support.

noor said...

شركة تنظيف في الكويت شركة تنظيف بالكويت
فني صحي فني صحي في الكويت
سباك الكويت سباك بالكويت

شركة تنظيف كنب الكويت تنظيف كنبات الكويت
ادوات صحيه الكويت ادوات صحيه الكويت
شركة غسيل سجاد الكويت غسيل سجاد الكويت
فني كهربائي منازل الكويت كهربائي منازل في الكويت

شركة تنظيف في الكويت شركة الكويت سيرفيس للتنظيف

Amania said...

Buy all the items in Auckland New Zealand. Treasurebox provide you all the house hold outdoor garden nzitems which will be easily available at low price..!

Nino Nurmadi , S.Kom said...

Al Qur'an Keutamaan Doa Abu Darda RA Syekh Abdul Qodir Jailani Rahmat Allah SWT Malaikat Mazhab Hanafi Shalat Tahajud Shalawat Nabi Muhammad Shallallahu 'Alaihi Wa SallamCara Wudhu Nabi Muhammad Saw

Teresa Halminton said...

I really like using Gmail but I can't solve my trouble without gmail email login, I think this website are gonna be helpful to you.

Unknown said...

Doing Good work. Keet it Up - Checkout Our List Of Best Gaming phone Under 15000

Unknown said...

Doing Good work. Keet it Up - Checkout Our List Of Best Gaming Phone Under 20000

Unknown said...

Confused which phone to buy after this coronavirus is over. - Checkout Our List Of
Samsung Upcoming Phones

Doing Good work. Keet it Up - Checkout Our List Of
Mi Upcoming Phones

Best external ssd for gaming

best gaming phone under 20000

Mi 11 Pro

best gaming phone under 15000

Redmi 10X

Term Paper Writing Services said...

Medical research paper writing services seekers have been on the rise lately since most learners need Medical Assignment Writing Services, medicine essay writing help and nursing essay writing services.

Kush Singh said...

Nice blog, it's truly a complete package of lots of information, although I have read hundreds of blogs on this topic, the way you present all the stuff here is truly commendable. In the end, I just want to say textsmashzone is the best place if you want bulk voice call services in Delhi. They are cheap, reliable and trustworthy bulk SMS service in Delhi as well as best Cheapest Transactional SMS Service Provider in Delhi.

Himah Hamih said...

Very interesting content which helps me to get the indepth knowledge.

online internship
online internships
watch internship online
online internship for students
the internship online
online internship with certificate
online internship certificate
python online internship
data science online internship said...

Very nicely written blog...Relly loved reading it...Please check my blogs for
Jaipur Escorts
Jaipur Escorts
Jaipur Escorts
Delhi Escorts
Guwahati Escorts
Guwahati Escorts
Guwahati Escorts
Guwahati Escorts
Lucknow Escorts
Aerocity Escorts

onlineAssignmenthelp said...

Assignment Help in Brisbane
Which is the best assignment help in Brisbane? Ans. is the best assignment help service in Brisbane. We have been offering See. Accounting assignment. Finance assignment , Social science assignment, Engineering assignment all See more=

onlineAssignmenthelp said...

amnamalik said...

onlineAssignmenthelp said...

Assignment Help in Australia
We provide online assignment help & writing services like dissertation/thesis, essay, case study, Australia for university and college students. Best Law assignment help team in Australia by Australian Students. Let the experts help with your assignment for High Distinction. Get Help Today!

onlineAssignmenthelp said...

Assignment Help in Adelaide
The Tutors Help is the best assignment writer in Adelaide We provide the most authentic assignment help service in Australia at affordable prices. assignments are written by experts

onlineAssignmenthelp said...

Assignment Help in Brisbane
Looking for the best assignment writing help in Brisbane? We, Assignment writing help experts are proud to announce that we also provide our amazing most significant advantage of taking assignment help in Brisbane is that these professionals guarantee an increase in grades.

onlineAssignmenthelp said...

Assignment Help in Adelaide
Get excellent Assignment Help in Adelaide by our The tutors help in Australia. Our The tutors help have the capability to write quality essays for you and deliver timely. WhatsApp +61 280062221

PGSLOT said...

หาเงินง่ายๆได้แล้ววันนี้เพียงคุณหันมาร่วมลงทุนกับเราที่เกม Cards Hi Lo เกมที่ถูกสร้างสรรค์มาอย่างดีเพื่อคุณ วิกฤตเศรษฐกิจครั้งนี้เราจะผ่านมันไปด้วยกัน ลงทุนเลยตอนนี้รับฟรีเครดิตสูงสุดหนึ่งร้อยเปอร์เซ็นต์สำหรับสมาชิกใหม่ แจกจริงแจกกระจายเหมือนให้กันฟรีๆ

Anne said...

แตกง่ายที่สุด แตกบ่อย แจกทุกวัน ไม่ว่าเกมไหน ไม่ว่าค่ายไหน คุณก็มีโอกาสถูกแจ็กพอตได้เช่นกัน เพราะเว็บของเรา เป็นเว็บไซต์ที่มีรางวัลแจ็คพอตที่โดนมากที่สุด ทุนน้อยก็มีสิทธิ์ลุ้นรางวัลใหญ่เช่นกัน เพราะไม่มีใครรู้ว่าแจ็คพอตจะออกมาเมื่อไหร่ คุณอาจเป็นคนที่โชคดี แค่เล่น ซุปเปอร์สล็อตกับเราก็มีสิทธิ์ลุ้นแจ็คพอตทุกวัน แตกง่าย. จ่ายจริงทุกวัน

koko said...

แจกเงินกระจาย มีโบนัสแจกให้กันแบบรัว ๆ เข้ามาร่วมสนุกกันเลยที่เกม Three Monkeys เกมสล็อตที่นำพาโดยเจ้าลิงน้อยทั้ง 3 ตน มีรางวัลมากมายมอบให้กับนักเดิมพัน สนใจ เชิญคลิก ภายในเกมพบกันสัญลักษณ์ของ Wild เป็นรูปเจ้าลิงน้อยสามตัว สามารถเทนได้ทุกสัญลักษณ์ยกเว้นสัญลักษณ์ของ Scatter ยิ่งเล่นก็ยิ่งรวยคุ้มกว่านี้ไม่มีอีกแล้ว

Chinkansen said...

แจ็คพอตแตะกระจาย อยากมีเงินใช้ไม่ขาดกระเป๋าเล่นเลยที่เกม Shaolin Soccer เกมสล็อตคุณภาพดีที่มาในธีมของนักเตะทีมกังฟู มีฟีเจอร์พิเศษและของรางวัลมากมายมอบให้แบบไม่อั้นทุกช่วงเวลา สนใจเชิญเข้ามาเลยที่ PGSLOT.SEXY เป็นเกมสล็อต 5 รีล 4 แถว มีไลน์ทั้งหมด 25 ไลน์ ได้เงินเร็ว สมัครเล่นตอนนี้รับเครดิตฟรีหนึ่งร้อยเปอร์เซ็นต์

Unknown said...