NServiceBus using static class library - nservicebus

I've got a static class library which I'm using to provide services to an ASP.NET MVC3 application.
I'm trying to get my head around the best way to provide async database calls. I've got an app that sends data to a node, which passes it on to all the nodes that node knows about and so on.
I'm using NServiceBus2 to accept a node message from a web client. Control is then sent back to the web app to allow the controller to finish and hence return the page to the user.
In the background a listener picks up that message and starts the node database trawl. I've created a new class library which is the listener which works fine.
My problem is publishing. Do I have to create the Bus on every call to a method? Where can I store the bus? I suppose I could try the WCF route?
Clarifications
I don't think it's a great idea to raise messages directly from a web application - in the same way you probably wouldn't put DB code in the controller. I'd like to have a separate class library that is the 'business logic'.

There are a couple of ways to get messages on the Bus from a ASP.NET web app. Firstly you can bootstrap the Bus once in a global place(global.asax or otherwise) and provide a reference to it. We prefer to reference the Bus via some abstraction, typically a class such as ServiceAgent<T> where T is a message you will internally Bus.Send(). If you don't want to boostrap the Bus in your web app, the other option is to expose your NServiceBus endpoint as a WCF service. This is done simply by implementing a class with the WcfService<TRequest,TResponse>. From there you can simply call the exposed SOAPy service. If you don't like SOAP, you can configure the endpoint differently. From within your endpoint you can then do a Publish().

you create a bus per service. a service can be a windows service, a win-forms application or in your case a website.
in a website/webservice scenario i normally create the bus in the application_start event of the global.asax.
you can save the bus in a container for example StructureMap or Castle Windsor.
don't publish messages from your website directly instead call a wcf service that publishes a message. or use send from your website. take your time to understand the different usages of messaging with nservicebus. specifically the differences of pub/sub and send/reply scenarios when to use what is essential.
to your other text: i don't understand your scenario. if you have further problems please edit your original post to help us understand.

Related

Service Bus in ASP.NET Core

I would like my ASP.NET Core application to send messages to a Azure Service Bus.
In Microsoft's article Best Practices for performance improvements using Service Bus Messaging they argue that you should re-use instances of clients.
It is recommended that you do not close messaging factories or queue, topic, and subscription clients after you send a message, and then re-create them when you send the next message.
So I take that as I should not instantiate a new instance of the client (TopicClient or QueueClient) inside my controller using the new keyword.
I guess that I should use dependency injection in ASP.NET Core.
Should I directly inject a TopicClient/QueueClient or should I create an own class that wraps an instance of the client and expose a SendAsync method?
When registering the service with dependency injector should I register it as a singleton?
We did it with a wrapper class that is then returning the TopicClient/QueueClient and registered it as a singleton and found no big issues with this approach.
We based our approach on this example provided by Microsoft eshopOnContainers.
The example code for this functionality is found in this file. They than register this class as singleton in Startup.cs in the services where they require ServiceBus.

Azure SignalR and Azure Web Application with multiple instances

We are developing ASP.Net core that is hosted as Azure Web Application.
We also use Azure SignalR service
Everything works great as long as we have single instance of the Web App, but once we scale it out we have the following problem:
From the Controller's action we resolve IHubContext and we send message to Hub's client. Everything works great so far
Hub's client accepts response and sends it TheHub endpoint.
The problem here is that response could be sent to another instance of Web App. So we send request from instance #1 but response is sent to instance #2 with 50% chance and instance #1 never receives response
Any ideas of how we could make it work so instance that emitted request actually received response?
SignalR has support for scaleout scenarios out of the box, it's called backplanes. The idea is that with help of one of backplane components, it will spread out SignalR events accross all instances. For Asp.Net framework, use one of these packages
Microsoft.AspNet.SignalR.ServiceBus3
Microsoft.AspNet.SignalR.ServiceBus
Microsoft.AspNet.SignalR.StackExchangeRedis
Microsoft.AspNet.SignalR.SqlServer
For ASP.Net Core only Redis is ported with Microsoft.AspNetCore.SignalR.StackExchangeRedis package, but there are some provided by community, see https://github.com/thomaslevesque/AspNetCore.SignalR.AzureServiceBus
public void ConfigureServices(IServiceCollection services)
{
services.AddSignalR()
.AddAzureSignalR(options =>
{
options.ApplicationName = "app1";
}
);
}
You could specify an ApplicationName in the server SDK for different server groups.
It will help your server generate access tokens like ......?hub=app1_<your_hub> during negotiation which can help our ASRS instances differentiate connections coming from different server groups
Unfortunately I didn't find reliable solution that wouldn't require a bit clumsy workarounds
But there are 2 solutions I could offer for this scenario
#LexLi suggested a good approach to solve this problem. So you basically can make your web app a SignalR client as well and make it a member of a group. This way every instance of web app is also a client and then instance that receives response for Hub's client can pass this response to group of web app instances
You could leverage Azure Service Bus topics. So once started instance will start subscribe to listen a topic. And then once any instance receives a response from Hub's client it would place response into Service Bus Topic and then every instance will receive this response from the topic
I was hoping that there could be a better solution for such problem

How to properly implement SignalR in a distributed, SOA environment?

I have a good understanding SignalR Hubs in a client/server scenario, where both the client and server are tightly coupled.
Let's say I have a WCF service that receives an update from some external resource. That service could update the database with a new value. However the client would need to be notified that an update has occurred. This could be handled through a service proxy that notifies the client (sounds a bit like polling) or some cache resource.
I could create C#-based clients and connect all the nodes via SignalR hubs, but this creates a closed, non-distributed system.
A SignaR hub that attaches to a WCF service could use the .Net 4.5 could implement a WCF asynchronous service operation, where a hub client would be notified with any service data changes.
I saw something similar in Push Notifications with NServiceBus and SignaR, but not sure if this is an optimal production-level solution.
What other methods could be used in this scenario and how would they be implemented?
If you are not using push notifications directly to the client or some kind of long polling then it is pretty typical to communicate with clients on another channel altogether. Not knowing the business case, it is hard to tell what would be feasible. Usually this manifests itself in the form of SMS, push notifications to mobile, email, etc. This does not answer your question directly, but you may find that there is another way to achieve your goal.

Publish event from service layer composed of web applications using service bus

I have read Why not publish NServiceBus messages from a web application and another similar question about this but I am not clear if this applies to service layer as well. For example, if the service layer is composed of web services or REST services built using WCF or Web API or any other way, should those services publish events or send commands? If those services are hosted in load balanced web servers, the problems outlined in the articles apply to this layer as well. How would the recommendation change or not change?
If I look from the definition of Event vs Command, the messages I am talking about are Events e.g. "a user was created" and so an event should be published. As a matter of fact, the service that created the user doesn't even know what else to do i.e. may be another application is supposed to create a customized portal for it and yet another application is supposed to send a welcome kit to the user. This would be an event and not a command. I guess I am hung up on the definition of a web application and application service when application service itself is composed of one or many web applications.
The definition of Web Application
A web application is an application that is accessed by users over a
network such as the Internet or an intranet.
However, to me, the users can be computers and thus web services are web applications and that is the reason for this question.
EDIT:
Let's consider a concrete example. An ASP.NET website (MVC or Web form - doesn't matter) displays the form to the operator, gets a post with data about user creation (Name, UserName, Password) and invokes a WCF service to create the user. In between website and WCF service we can put ServiceBus and send command to create the user (Request/Response) so that we get all the benefits described in the first article. WCF service is the actual business processing layer i.e. it would create the user. That is where I have the question. After the user is created, it should announce that a user has been created and other systems can react to it and do whatever they are supposed to do. So it fits perfectly the pattern of publish the message. However, the WCF service itself is a web application and thus has most of the traits of the web applications and thus the confusion.
As mentioned in the answer to the SO question you linked to, publishing event has more to do with where the actual processing takes places. Just as a side-note: it is not a matter of Send instead of Publish since that would imply that the two are interchangeable whereas they have rather different intentions. When you want to publish, you want to publish.
The same questions should arise if you find yourself publishing from your web-exposed integration layer: should you be performing the business processing in that code or rather sending it off to another endpoint for processing? Typically you should just send it off to another endpoint. You may even consider how you would perform the relevant action should anyone wish to invoke it. For instance, if you are publishing a UserCreatedEvent message it implies that you created a user. How would a user be created? Would I be forced to use the WCF / Web-Api layer or can I send a CreateUserCommand message on the bus that is processed by some application endpoint? If it is the former then you may need to rethink your design. However, if the latter you should be sending the command from your WCF / Web-Api anyway and the processing endpoint will perform the Publish bit :)
update:
My take on it is that it is more about cohesion / concerns. You would typically interact with your domain, from within your business, via a service bus for commands and events, and a simple query layer for reads. If you need to expose anything to a third-party (or simply via the web) then you use WCF / WS / Web-APi. The point is that you should try to avoid business processing in an integration endpoint (or in a front-end like a website). Business processing is better suited to application servers. There are usually exceptions to the rule but if you are in a position to influence the structure then you are in a better space.
The fact is, whatever code is truly responsible for performing the action should be the same which publishes the event. If you've got a MVC app and in the controller itself you're using Entity Framework to insert the User record, then that is exactly where the Publish should be, right after the SaveChanges call. If however, the controller calls a referenced binary or service which does the actions involved in the "add user" call, then the Publish should be there. My thought is the event should be right alongside the code that does the action whose event you are trying to publish.

Build subscription alerts for service changes

I am using Biztalk UDDI V3 (stand-alone install) on a windows 2008. I have configured all services (web, database and subscription):
I successfully published a couple of services
I successfully accessed and retrieved service information from my .net console application.
My issue at this point is with the subscription service. I tried to subscribe to one of the published services only to find out that I need to create my own listener.
I followed the steps listed here. Please take a look at the section entitled "Building subscription alerts for service changes". I am confused as to what the WCF service I create is supposed to look like. The instructions state the following:
Now we create a new WCF Service project and reference this existing service library. After making sure the .svc file points to our referenced library object, and adding a valid endpoint configuration file, view our service in the web browser to ensure that it's up and running.
I find this section confusing. Not sure what public methods would the WCF service expose(if any at all) or how to expose the functionality within the service library that I just referenced from within my WCF project.
Of course, if you know of a different way to achieve what I am trying to accomplish, that also would be much appreciated.
Thank you.
This may help. I actually just wrote a complete port for Apache jUDDI's client library using .NET C#. One of the use cases is actually what you are attempting to do. Here's the rough approach used.
Generate the code from wsdl (using wsdl.exe, because svcutil doesn't like the UDDI wsdls)
Alter the interface code to have WCF bindings for the Subscription Listener class
Create an implementation of the subscription listener and handle the callbacks
Fire up the implementation using WCF's embedded service
Register your sub listener endpoint with UDDI (using the correct annotations per the spec)
Setup the subscription using your sub listener's binding template
Wait for callbacks
Here's the code
http://svn.apache.org/repos/asf/juddi/trunk/juddi-client.net/
Example
http://svn.apache.org/repos/asf/juddi/trunk/juddi-client.net/juddi-client.net-sample/org.apache.juddi.client.samples/SubscriptionCallbackExample.cs
There's also a Java version that does the exact same thing.