Dapr Pub-Sub with .NET Core Sample (without using Dapr Dotnet-SDK)
This sample includes 3 .NET Core WebApi as below:
- 1 publisher
Example.Dapr.Publisher
- 2 subcribers:
Example.Dapr.FirstSubscriber
will subscribe on ProductCreated topicExample.Dapr.SecondSubscriber
will subscribe on ProductCreated topic
- Install Docker for Desktop
- Install Dapr Cli
- Please see the Guide
-
Starting Publisher
cd .\source\Example.Dapr.Publisher\
dapr run --app-id example-publisher --app-port 5000 dotnet run
-
Starting FirstSubscriber
cd .\source\Example.Dapr.FirstSubscriber\
dapr run --app-id example-first-subscriber --app-port 5001 dotnet run
-
Starting SecondSubscriber
cd .\source\Example.Dapr.SecondSubscriber\
dapr run --app-id example-second-subscriber --app-port 5002 dotnet run
dapr publish --topic ProductCreated --payload "{ \"ProductId\": 1, \"Code\":\"this-is-a-test\" }"
Both subscribers which are example-first-subscriber & example-second-subscriber receive a message
- RestClient extension must be installed within Visual Studio Code
- Open vscode-rest-test\create-product.http by Visual Studio Code; then click on Send Request and observe the log
- Since we subscribe on ProductCreated topic, hence we have to define the endpoint as below
[HttpPost("ProductCreated")]
public IActionResult SubscribeProductCreated(CloudEvent request)
- Remember add
CloudEventJsonInputFormatter
services
.AddControllers(opts =>
{
opts.InputFormatters.Insert(0, new CloudEventJsonInputFormatter());
})
.AddJsonOptions(opts => opts.JsonSerializerOptions.PropertyNameCaseInsensitive = true);
- Then expose to Dapr runtime by define the MapGet inside Startup.cs
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapGet("/dapr/subscribe", async context =>
{
var channels = new[] { "ProductCreated" };
var toJson = JsonSerializer.Serialize(channels);
context.Response.ContentType = "application/json";
await context.Response.WriteAsync(toJson);
});
});
- First, we define the
DaprPublisher
as Http Client inStartup.cs
services
.AddHttpClient<DaprPublisher>((provider, client) =>
{
var logger = provider.GetRequiredService<ILogger<Startup>>();
var daprPort = Environment.GetEnvironmentVariable("DAPR_HTTP_PORT") ?? "3500";
var baseAddress = $"http://localhost:{daprPort}";
logger.LogInformation($"[{nameof(Startup)}] - Publish Address: {baseAddress}");
client.BaseAddress = new Uri(baseAddress, UriKind.Absolute);
});
- Then, in order to publish the message to ProductCreated topic, we just simply make a POST request to
http://localhost:{DAPR_HTTP_PORT}/v1.0/publish/ProductCreated
. See the code at DaprPublisher.cs
If you liked this project or if it helped you, please give a star ⭐ for this repository. Thank you!!!