### Install In-Memory Storage and Message Queue Source: https://github.com/dotnetcore/cap/blob/master/docs/content/user-guide/en/getting-started/quick-start.md Install packages for in-memory storage and message queue for a quick start setup. ```powershell PM> Install-Package DotNetCore.CAP.InMemoryStorage PM> Install-Package Savorboard.CAP.InMemoryMessageQueue ``` -------------------------------- ### Minimum CAP Configuration Source: https://github.com/dotnetcore/cap/blob/master/docs/content/user-guide/en/cap/configuration.md Configure at least one transport and one storage. This example uses in-memory queue and storage for quick setup. ```csharp services.AddCap(capOptions => { capOptions.UseInMemoryQueue(); // Requires the Savorboard.CAP.InMemoryMessageQueue NuGet package. capOptions.UseInMemoryStorage(); }); ``` -------------------------------- ### Install MySQL Package Source: https://github.com/dotnetcore/cap/blob/master/docs/content/user-guide/en/storage/mysql.md Install the necessary NuGet package for MySQL support. ```powershell PM> Install-Package DotNetCore.CAP.MySql ``` -------------------------------- ### Install CAP Package Source: https://github.com/dotnetcore/cap/blob/master/docs/content/user-guide/en/getting-started/quick-start.md Install the main CAP package using Package Manager Console. ```powershell PM> Install-Package DotNetCore.CAP ``` -------------------------------- ### Install CAP OpenTelemetry Package Source: https://github.com/dotnetcore/cap/blob/master/docs/content/user-guide/en/monitoring/opentelemetry.md Install the CAP OpenTelemetry package using the .NET CLI. ```bash dotnet add package DotNetCore.CAP.OpenTelemetry ``` -------------------------------- ### Install InMemoryStorage Package Source: https://github.com/dotnetcore/cap/blob/master/docs/content/user-guide/en/storage/in-memory-storage.md Install the DotNetCore.CAP.InMemoryStorage package using the Package Manager Console. ```powershell PM> Install-Package DotNetCore.CAP.InMemoryStorage ``` -------------------------------- ### Install In-Memory Queue NuGet Package Source: https://github.com/dotnetcore/cap/blob/master/docs/content/user-guide/en/transport/in-memory-queue.md Install the Savorboard.CAP.InMemoryMessageQueue package using the Package Manager Console. ```powershell PM> Install-Package Savorboard.CAP.InMemoryMessageQueue ``` -------------------------------- ### Install PostgreSQL Package Source: https://github.com/dotnetcore/cap/blob/master/docs/content/user-guide/en/storage/postgresql.md Install the PostgreSQL NuGet package for CAP. This is the first step to enable PostgreSQL storage. ```powershell PM> Install-Package DotNetCore.CAP.PostgreSql ``` -------------------------------- ### Install CAP Kafka Package Source: https://github.com/dotnetcore/cap/blob/master/docs/content/user-guide/en/transport/kafka.md Install the necessary NuGet package for Kafka integration. ```powershell PM> Install-Package DotNetCore.CAP.Kafka ``` -------------------------------- ### Install RabbitMQ NuGet Package Source: https://github.com/dotnetcore/cap/blob/master/docs/content/user-guide/en/transport/rabbitmq.md Install the necessary NuGet package for RabbitMQ integration with CAP. ```powershell PM> Install-Package DotNetCore.CAP.RabbitMQ ``` -------------------------------- ### Install SQL Server Package Source: https://github.com/dotnetcore/cap/blob/master/docs/content/user-guide/en/storage/sqlserver.md Install the necessary NuGet package for SQL Server integration with CAP. ```powershell PM> Install-Package DotNetCore.CAP.SqlServer ``` -------------------------------- ### Install Pulsar NuGet Package Source: https://github.com/dotnetcore/cap/blob/master/docs/content/user-guide/en/transport/pulsar.md Install the DotNetCore.CAP.Pulsar package using the Package Manager Console. ```powershell PM> Install-Package DotNetCore.CAP.Pulsar ``` -------------------------------- ### Install NATS Package Source: https://github.com/dotnetcore/cap/blob/master/docs/content/user-guide/en/transport/nats.md Install the DotNetCore.CAP.NATS NuGet package using the Package Manager Console. ```powershell PM> Install-Package DotNetCore.CAP.NATS ``` -------------------------------- ### Kubernetes ServiceAccount, ClusterRole, and Deployment Example Source: https://github.com/dotnetcore/cap/blob/master/docs/content/user-guide/en/monitoring/kubernetes.md Example YAML for creating a ServiceAccount, ClusterRole, and Deployment to grant CAP access to the Kubernetes API for listing namespaces and services. ```yaml apiVersion: v1 kind: ServiceAccount metadata: name: api-access --- apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRole metadata: name: ns-svc-reader rules: - apiGroups: [""] resources: ["namespaces", "services"] verbs: ["get", "watch", "list"] --- apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRoleBinding metadata: name: read-pods subjects: - kind: ServiceAccount name: api-access namespace: default roleRef: kind: ClusterRole name: ns-svc-reader apiGroup: rbac.authorization.k8s.io --- apiVersion: apps/v1 kind: Deployment metadata: name: api-access-deployment spec: replicas: 1 selector: matchLabels: app: api-access-app template: metadata: labels: app: api-access-app spec: serviceAccountName: api-access containers: - name: api-access-container image: your_image --- apiVersion: v1 kind: Service metadata: name: api-access-service spec: selector: app: api-access-app ports: - protocol: TCP port: 80 targetPort: 80 ``` -------------------------------- ### Configure In-Memory Message Queue in Startup.cs Source: https://github.com/dotnetcore/cap/blob/master/docs/content/user-guide/en/transport/in-memory-queue.md Add the UseInMemoryMessageQueue() configuration to your CAP setup in the ConfigureServices method. ```csharp public void ConfigureServices(IServiceCollection services) { // ... services.AddCap(x => { x.UseInMemoryMessageQueue(); // x.UseXXX ... }); } ``` -------------------------------- ### Kafka Main Configuration Example Source: https://github.com/dotnetcore/cap/blob/master/docs/content/user-guide/en/transport/kafka.md Set additional native Kafka configuration options using MainConfig. ```csharp services.AddCap(capOptions => { capOptions.UseKafka(kafkaOption=> { // kafka options. // kafkaOptions.MainConfig.Add("", ""); }); }); ``` -------------------------------- ### Install CAP Storage Providers Source: https://github.com/dotnetcore/cap/blob/master/README.md Install NuGet packages for your chosen database storage provider (e.g., SQL Server, MySQL, PostgreSQL, MongoDB). ```shell PM> Install-Package DotNetCore.CAP.SqlServer ``` ```shell PM> Install-Package DotNetCore.CAP.MySql ``` ```shell PM> Install-Package DotNetCore.CAP.PostgreSql ``` ```shell PM> Install-Package DotNetCore.CAP.MongoDB // Requires MongoDB 4.0+ cluster ``` -------------------------------- ### Install Dashboard Dependencies Source: https://github.com/dotnetcore/cap/blob/master/src/DotNetCore.CAP.Dashboard/wwwroot/README.md Installs the necessary packages for the dashboard project using npm. Navigate to the dashboard's wwwroot directory before running. ```sh npm install ``` -------------------------------- ### Install CAP Dashboard Package Source: https://github.com/dotnetcore/cap/blob/master/README.md Install the CAP Dashboard NuGet package using the Package Manager Console. ```powershell PM> Install-Package DotNetCore.CAP.Dashboard ``` -------------------------------- ### Install Redis Streams Package Source: https://github.com/dotnetcore/cap/blob/master/docs/content/user-guide/en/transport/redis-streams.md Install the necessary NuGet package for Redis Streams integration with CAP. ```powershell PM> Install-Package DotNetCore.CAP.RedisStreams ``` -------------------------------- ### Run Dashboard Development Server Source: https://github.com/dotnetcore/cap/blob/master/src/DotNetCore.CAP.Dashboard/wwwroot/README.md Starts the dashboard development server. Ensure the backend API allows cross-domain access. ```sh npm run dev ``` -------------------------------- ### Install CAP Transport Providers Source: https://github.com/dotnetcore/cap/blob/master/README.md Install NuGet packages for your chosen message transport (e.g., Kafka, RabbitMQ, Azure Service Bus). ```shell PM> Install-Package DotNetCore.CAP.Kafka ``` ```shell PM> Install-Package DotNetCore.CAP.RabbitMQ ``` ```shell PM> Install-Package DotNetCore.CAP.AzureServiceBus ``` ```shell PM> Install-Package DotNetCore.CAP.AmazonSQS ``` ```shell PM> Install-Package DotNetCore.CAP.NATS ``` ```shell PM> Install-Package DotNetCore.CAP.RedisStreams ``` ```shell PM> Install-Package DotNetCore.CAP.Pulsar ``` -------------------------------- ### Install MongoDB Storage Package Source: https://github.com/dotnetcore/cap/blob/master/docs/content/user-guide/en/storage/mongodb.md Install the MongoDB storage package for CAP using the NuGet Package Manager Console. ```powershell PM> Install-Package DotNetCore.CAP.MongoDB ``` -------------------------------- ### Install CAP AmazonSQS NuGet Package Source: https://github.com/dotnetcore/cap/blob/master/docs/content/user-guide/en/transport/aws-sqs.md Installs the necessary NuGet package to enable AWS SQS transport for CAP. ```shell Install-Package DotNetCore.CAP.AmazonSQS ``` -------------------------------- ### Kubernetes ServiceAccount, Role, and Deployment Example (Namespace Scoped) Source: https://github.com/dotnetcore/cap/blob/master/docs/content/user-guide/en/monitoring/kubernetes.md Example YAML for creating a ServiceAccount, Role, and Deployment to grant CAP access to the Kubernetes API for listing services only within the dashboard's namespace. ```yaml apiVersion: rbac.authorization.k8s.io/v1 kind: Role metadata: name: ns-svc-reader rules: - apiGroups: [""] resources: ["services"] verbs: ["get", "watch", "list"] --- apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRoleBinding metadata: name: read-pods subjects: - kind: ServiceAccount name: api-access namespace: default roleRef: kind: ClusterRole name: ns-svc-reader apiGroup: rbac.authorization.k8s.io ``` -------------------------------- ### Install Azure Service Bus NuGet Package Source: https://github.com/dotnetcore/cap/blob/master/docs/content/user-guide/en/transport/azure-service-bus.md Install the CAP Azure Service Bus transport package using the NuGet Package Manager Console. ```powershell PM> Install-Package DotNetCore.CAP.AzureServiceBus ``` -------------------------------- ### Custom Headers Builder Example Source: https://github.com/dotnetcore/cap/blob/master/docs/content/user-guide/en/transport/nats.md Define custom headers for messages sent from heterogeneous systems to ensure subscriber compatibility. ```csharp x.UseNATS(aa => { aa.CustomHeadersBuilder = (e, sp) => [ new(DotNetCore.CAP.Messages.Headers.MessageId, sp.GetRequiredService().NextId().ToString()), new(DotNetCore.CAP.Messages.Headers.MessageName, e.Message.Subject) ]; }); ``` -------------------------------- ### Configure Dashboard with Open ID Connect Authentication Source: https://github.com/dotnetcore/cap/blob/master/docs/content/user-guide/en/monitoring/dashboard.md Configures the Dashboard to use OpenID Connect for authentication. Requires custom authorization policy setup. ```csharp services .AddAuthorization(options => { options.AddPolicy(DashboardAuthorizationPolicy, policy => policy .AddAuthenticationSchemes(OpenIdConnectDefaults.AuthenticationScheme) .RequireAuthenticatedUser()); }) .AddAuthentication(opt => opt.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie() .AddOpenIdConnect(options => { ... }); services.AddCap(cap => { cap.UseDashboard(d => { d.AuthorizationPolicy = DashboardAuthorizationPolicy; }); cap.UseInMemoryStorage(); cap.UseInMemoryMessageQueue(); }); ``` -------------------------------- ### Run Consul Agent Source: https://github.com/dotnetcore/cap/blob/master/docs/content/user-guide/en/monitoring/consul.md Command to start a Consul agent in development mode. This is necessary for service discovery to function. ```bash consul agent -dev ``` -------------------------------- ### Setting Default Subscription Group in Configuration Source: https://github.com/dotnetcore/cap/blob/master/README.md Configure a default group name for all subscribers within the CAP service setup. ```csharp services.AddCap(x => { x.DefaultGroup = "my-default-group"; }); ``` -------------------------------- ### Configure CAP Services in Startup.cs Source: https://github.com/dotnetcore/cap/blob/master/docs/content/user-guide/en/getting-started/quick-start.md Configure CAP services in Startup.cs using in-memory storage and message queue. ```csharp public void ConfigureServices(IServiceCollection services) { services.AddCap(x => { x.UseInMemoryStorage(); x.UseInMemoryMessageQueue(); }); } ``` -------------------------------- ### Configure RabbitMQ Transport in Startup.cs Source: https://github.com/dotnetcore/cap/blob/master/docs/content/user-guide/en/transport/rabbitmq.md Add RabbitMQ configuration to the AddCap method in your Startup.cs file. ```csharp public void ConfigureServices(IServiceCollection services) { // ... services.AddCap(x => { x.UseRabbitMQ(opt=> { //RabbitMQOptions }); // x.UseXXX ... }); } ``` -------------------------------- ### Build Docs Site Locally with Docker Source: https://github.com/dotnetcore/cap/blob/master/docs/readme.md Navigate to the docs directory and run this command to build and serve the documentation site locally using Docker. It maps the current directory to the container and exposes port 8000. ```bash cd CAP/docs docker run --rm -it -p 8000:8000 -v ${PWD}:/docs squidfunk/mkdocs-material ``` -------------------------------- ### Configure MongoDB in Startup.cs Source: https://github.com/dotnetcore/cap/blob/master/docs/content/user-guide/en/storage/mongodb.md Add MongoDB configuration to the ConfigureServices method in Startup.cs to enable CAP with MongoDB storage. ```csharp public void ConfigureServices(IServiceCollection services) { // ... services.AddCap(x => { x.UseMongoDB(opt=>{ //MongoDBOptions }); // x.UseXXX ... }); } ``` -------------------------------- ### Configure In-Memory Storage in Startup.cs Source: https://github.com/dotnetcore/cap/blob/master/docs/content/user-guide/en/storage/in-memory-storage.md Configure in-memory storage by calling `UseInMemoryStorage()` within the `AddCap` configuration in your `Startup.cs` file. ```csharp public void ConfigureServices(IServiceCollection services) { // ... services.AddCap(x => { x.UseInMemoryStorage(); // x.UseXXX ... }); } ``` -------------------------------- ### Configure CAP Services Source: https://github.com/dotnetcore/cap/blob/master/README.md Configure CAP services in `Startup.cs` or `Program.cs`, specifying ORM, storage, and message transport. ```csharp public void ConfigureServices(IServiceCollection services) { // If you are using EF as the ORM services.AddDbContext(); // If you are using MongoDB services.AddSingleton(new MongoClient("...")); services.AddCap(x => { // Using Entity Framework // CAP can auto-discover the connection string x.UseEntityFramework(); // Using ADO.NET x.UseSqlServer("Your ConnectionString"); x.UseMySql("Your ConnectionString"); x.UsePostgreSql("Your ConnectionString"); // Using MongoDB (requires a 4.0+ cluster) x.UseMongoDB("Your ConnectionString"); // Choose your message transport x.UseRabbitMQ("HostName"); x.UseKafka("ConnectionString"); x.UseAzureServiceBus("ConnectionString"); x.UseAmazonSQS(options => { /* ... */ }); x.UseNATS("ConnectionString"); x.UsePulsar("ConnectionString"); x.UseRedisStreams("ConnectionString"); }); } ``` -------------------------------- ### Configure PostgreSQL Services Source: https://github.com/dotnetcore/cap/blob/master/docs/content/user-guide/en/storage/postgresql.md Add PostgreSQL configuration to your Startup.cs ConfigureServices method. This enables CAP to use PostgreSQL for storage. ```csharp public void ConfigureServices(IServiceCollection services) { // ... services.AddCap(x => { x.UsePostgreSql(opt=>{ //PostgreSqlOptions }); // x.UseXXX ... }); } ``` -------------------------------- ### Configure CAP with Kafka Source: https://github.com/dotnetcore/cap/blob/master/docs/content/user-guide/en/transport/kafka.md Add Kafka configuration to the ConfigureServices method in Startup.cs. ```csharp public void ConfigureServices(IServiceCollection services) { // ... services.AddCap(x => { x.UseKafka(opt=>{ //KafkaOptions }); // x.UseXXX ... }); } ``` -------------------------------- ### Configure MySQL Services Source: https://github.com/dotnetcore/cap/blob/master/docs/content/user-guide/en/storage/mysql.md Add MySQL configuration to your application's services in Startup.cs. ```csharp public void ConfigureServices(IServiceCollection services) { // ... services.AddCap(x => { x.UseMySql(opt=>{ //MySqlOptions }); // x.UseXXX ... }); } ``` -------------------------------- ### Configure CAP to Use AmazonSQS Source: https://github.com/dotnetcore/cap/blob/master/docs/content/user-guide/en/transport/aws-sqs.md Configures the CAP service in Startup.cs to use Amazon SQS as its transport mechanism. This involves adding the UseAmazonSQS extension method. ```csharp public void ConfigureServices(IServiceCollection services) { // ... services.AddCap(x => { x.UseAmazonSQS(opt=> { //AmazonSQSOptions }); // x.UseXXX ... }); } ``` -------------------------------- ### Naturally Idempotent Operations Source: https://github.com/dotnetcore/cap/blob/master/docs/content/user-guide/en/cap/idempotence.md Examples of operations that are inherently idempotent, such as marking an object as deleted or updating a period. These can be directly applied to domain objects. ```csharp obj.MarkAsDeleted(); ``` ```csharp obj.UpdatePeriod(message.NewPeriod); ``` -------------------------------- ### Configure Pulsar Transport in Startup.cs Source: https://github.com/dotnetcore/cap/blob/master/docs/content/user-guide/en/transport/pulsar.md Add Pulsar configuration to the ConfigureServices method in Startup.cs to enable it as a CAP transporter. ```csharp public void ConfigureServices(IServiceCollection services) { // ... services.AddCap(x => { x.UsePulsar(opt => { //Pulsar options }); // x.UseXXX ... }); } ``` -------------------------------- ### Publish with MongoDB Transaction Source: https://github.com/dotnetcore/cap/blob/master/docs/content/user-guide/en/storage/mongodb.md Example of publishing a message within a local MongoDB transaction using CAP. Ensure the database and collection are pre-created as MongoDB does not auto-create them within transactions. ```csharp // NOTE: Before testing, you need to create the database and collection first. // MongoDB cannot automatically create databases and collections within transactions, // so you must create them separately. For example, insert a record to auto-create the collection. //var mycollection = _client.GetDatabase("test") // .GetCollection("test.collection"); //mycollection.InsertOne(new BsonDocument { { "test", "test" } }); using (var session = _client.StartTransaction(_capBus, autoCommit: false)) { var collection = _client.GetDatabase("test") .GetCollection("test.collection"); collection.InsertOne(session, new BsonDocument { { "hello", "world" } }); _capBus.Publish("sample.rabbitmq.mongodb", DateTime.Now); session.CommitTransaction(); } ``` -------------------------------- ### Run ASP.NET Core Applications with Consul Configuration Source: https://github.com/dotnetcore/cap/blob/master/docs/content/user-guide/en/monitoring/consul.md These commands demonstrate how to set environment variables for hostname and port, and then run ASP.NET Core applications with specific node IDs and names for Consul registration. Ensure your database connection strings are correctly configured. ```powershell set ASPNETCORE_HOSTNAME=localhost&& set ASPNETCORE_PORT=5001&& dotnet run --urls=http://localhost:5001 NodeId=1 NodeName=CAP-1 ConnectionString="Server=localhost;Database=aaa;UserId=xxx;Password=xxx;" set ASPNETCORE_HOSTNAME=localhost&& set ASPNETCORE_PORT=5002&& dotnet run --urls=http://localhost:5002 NodeId=2 NodeName=CAP-2 ConnectionString="Server=localhost;Database=bbb;UserId=xxx;Password=xxx;" ``` -------------------------------- ### Configure Azure Service Bus in Startup.cs Source: https://github.com/dotnetcore/cap/blob/master/docs/content/user-guide/en/transport/azure-service-bus.md Configure CAP to use Azure Service Bus as a message transporter within the `ConfigureServices` method. Ensure you have the correct pricing tier for Service Bus. ```csharp public void ConfigureServices(IServiceCollection services) { // ... services.AddCap(x => { x.UseAzureServiceBus(opt=> { //AzureServiceBusOptions }); // x.UseXXX ... }); } ``` -------------------------------- ### Configure NATS Service Source: https://github.com/dotnetcore/cap/blob/master/docs/content/user-guide/en/transport/nats.md Add NATS configuration to the ConfigureServices method in Startup.cs. ```csharp public void ConfigureServices(IServiceCollection services) { services.AddCap(capOptions => { capOptions.UseNATS(natsOptions=>{ //NATS Options }); }); } ``` -------------------------------- ### Build Dashboard for Production Source: https://github.com/dotnetcore/cap/blob/master/src/DotNetCore.CAP.Dashboard/wwwroot/README.md Builds the dashboard project for release. The output will be placed in the 'dist' folder and embedded into the dashboard's csproj assembly. ```sh npm run build ``` -------------------------------- ### Configure SQL Server Services Source: https://github.com/dotnetcore/cap/blob/master/docs/content/user-guide/en/storage/sqlserver.md Add SQL Server configuration to your application's `ConfigureServices` method. This sets up CAP to use SQL Server as its data store. ```csharp public void ConfigureServices(IServiceCollection services) { // ... services.AddCap(x => { x.UseSqlServer(opt=>{ //SqlServerOptions }); // x.UseXXX ... }); } ``` -------------------------------- ### Enable CAP Dashboard and Kubernetes Discovery Source: https://github.com/dotnetcore/cap/blob/master/docs/content/user-guide/en/monitoring/kubernetes.md Configure CAP to use its dashboard and enable Kubernetes service discovery. ```csharp services.AddCap(x => { // ... x.UseDashboard(); x.UseK8sDiscovery(); }); ``` -------------------------------- ### Async Subscription Method Source: https://github.com/dotnetcore/cap/blob/master/README.md Implement asynchronous message handling by returning a Task and accepting a CancellationToken. ```csharp public class AsyncSubscriber : ICapSubscribe { [CapSubscribe("topic.name")] public async Task ProcessAsync(Message message, CancellationToken cancellationToken) { await SomeOperationAsync(message, cancellationToken); } } ``` -------------------------------- ### Subscribe to Message in Business Service Source: https://github.com/dotnetcore/cap/blob/master/README.md Implement `ICapSubscribe` interface and decorate the handler method with `[CapSubscribe]` for subscribers not located in controllers. Ensure the service is registered in `Startup.cs`. ```csharp namespace BusinessCode.Service { public interface ISubscriberService { void CheckReceivedMessage(DateTime datetime); } public class SubscriberService : ISubscriberService, ICapSubscribe { [CapSubscribe("xxx.services.show.time")] public void CheckReceivedMessage(DateTime datetime) { // Handle the message } } } ``` ```csharp public void ConfigureServices(IServiceCollection services) { services.AddTransient(); services.AddCap(x => { // ... }); } ``` -------------------------------- ### Configure Kubernetes Discovery to Show Only Explicitly Visible Nodes Source: https://github.com/dotnetcore/cap/blob/master/docs/content/user-guide/en/monitoring/kubernetes.md Configure CAP's Kubernetes discovery to only list services with the 'dotnetcore.cap.visibility: show' label. ```csharp services.AddCap(x => { // ... x.UseK8sDiscovery(opt => { opt.ShowOnlyExplicitVisibleNodes = true; }); }); ``` -------------------------------- ### Connect to RabbitMQ Cluster Source: https://github.com/dotnetcore/cap/blob/master/docs/content/user-guide/en/transport/rabbitmq.md Configure RabbitMQ to connect to a cluster using a comma-separated connection string. ```csharp x=> x.UseRabbitMQ("localhost:5672,localhost:5673,localhost:5674") ``` -------------------------------- ### Configure Dashboard with Custom Authentication Scheme Source: https://github.com/dotnetcore/cap/blob/master/docs/content/user-guide/en/monitoring/dashboard.md Sets up a custom authentication scheme and policy for the CAP Dashboard. Requires defining the custom scheme and handler. ```csharp const string MyDashboardAuthenticationPolicy = "MyDashboardAuthenticationPolicy"; services.AddAuthorization(options => { options.AddPolicy(MyDashboardAuthenticationPolicy, policy => policy .AddAuthenticationSchemes(MyDashboardAuthenticationSchemeDefaults.Scheme) .RequireAuthenticatedUser()); }) .AddAuthentication() .AddScheme(MyDashboardAuthenticationSchemeDefaults.Scheme, null); services.AddCap(cap => { cap.UseDashboard(d => { d.AuthorizationPolicy = MyDashboardAuthenticationPolicy; }); cap.UseInMemoryStorage(); cap.UseInMemoryMessageQueue(); }); ``` -------------------------------- ### Configure RabbitMQ ConnectionFactory Options Source: https://github.com/dotnetcore/cap/blob/master/docs/content/user-guide/en/transport/rabbitmq.md Set native RabbitMQ client ConnectionFactory options using ConnectionFactoryOptions. ```csharp services.AddCap(x => { x.UseRabbitMQ(o => { o.HostName = "localhost"; o.ConnectionFactoryOptions = opt => { //rabbitmq client ConnectionFactory config }; }); }); ``` -------------------------------- ### Configure CAP with a Table Prefix for Shared Databases Source: https://github.com/dotnetcore/cap/blob/master/docs/content/user-guide/en/samples/faq.md Use a table prefix to differentiate data when multiple applications share the same database with CAP. This is configured within the `AddCap` options. ```csharp public void ConfigureServices(IServiceCollection services) { services.AddCap(x => { x.UseKafka(""); x.UseMySql(opt => { opt.ConnectionString = "connection string"; opt.TableNamePrefix = "appone"; // Use different table name prefix here }); }); } ``` -------------------------------- ### Configure Redis Connection Options Source: https://github.com/dotnetcore/cap/blob/master/docs/content/user-guide/en/transport/redis-streams.md Set native Redis configuration options, such as connection endpoints, using StackExchange.Redis ConfigurationOptions. ```csharp services.AddCap(capOptions => { capOptions.UseRedis(redisOptions=> { // redis options. redisOptions.Configuration.EndPoints.Add(IPAddress.Loopback, 0); }); }); ``` -------------------------------- ### CAP Dashboard Initialization Source: https://github.com/dotnetcore/cap/blob/master/src/DotNetCore.CAP.Dashboard/wwwroot/dist/index.html Initializes the CAP Dashboard by setting the server URL and polling interval based on server-side configuration. ```javascript window.serverUrl = window.location.origin + "% (servicePrefix)"; window.pollingInterval = "% (pollingInterval)"; ``` -------------------------------- ### Partial Topic Subscription Source: https://github.com/dotnetcore/cap/blob/master/README.md Define a partial topic at the class level to group related method-level subscriptions. The final topic is a combination of class and method topics. ```csharp [CapSubscribe("customers")] public class CustomersSubscriberService : ICapSubscribe { [CapSubscribe("create", isPartial: true)] public void Create(Customer customer) { // ... } } ``` -------------------------------- ### NATS Client Configuration Options Source: https://github.com/dotnetcore/cap/blob/master/docs/content/user-guide/en/transport/nats.md Set additional native NATS configuration options using the Options parameter. ```csharp services.AddCap(capOptions => { capOptions.UseNATS(natsOptions=> { // NATS options. natsOptions.Options.Url=""; }); }); ``` -------------------------------- ### Azure Service Bus Emulator Configuration Source: https://github.com/dotnetcore/cap/blob/master/README.md Configure CAP to use the Azure Service Bus emulator by setting ConnectionString and AutoProvision to false. Ensure entities are pre-created. ```csharp services.AddCap(x => { x.UseAzureServiceBus(opt => { opt.ConnectionString = "Endpoint=sb://localhost;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=SAS_KEY_VALUE;UseDevelopmentEmulator=true;"; opt.AutoProvision = false; }); }); ``` -------------------------------- ### Monitor CAP Metrics with dotnet-counters Source: https://github.com/dotnetcore/cap/blob/master/docs/content/user-guide/en/monitoring/diagnostics.md Use the dotnet-counters tool to monitor CAP's EventSource metrics. Specify the process ID and the counter name to observe performance data. ```powershell dotnet-counters ps dotnet-counters monitor --process-id=25496 --counters=DotNetCore.CAP.EventCounter ``` -------------------------------- ### Publishing a Message with Callback Name Source: https://github.com/dotnetcore/cap/blob/master/docs/content/user-guide/en/cap/messaging.md Publish a message and specify a callback name for the consumer to respond to. This is useful for point-to-point consumption where the publisher needs to know the consumer's result. ```csharp // ============= Publisher ================= _capBus.Publish("place.order.qty.deducted", contentObj: new { OrderId = 1234, ProductId = 23255, Qty = 1 }, callbackName: "place.order.mark.status"); // publisher using `callbackName` to subscribe consumer result [CapSubscribe("place.order.mark.status")] public void MarkOrderStatus(JsonElement param) { var orderId = param.GetProperty("OrderId").GetInt32(); var isSuccess = param.GetProperty("IsSuccess").GetBoolean(); if(isSuccess){ // mark order status to succeeded } else{ // mark order status to failed } } // ============= Consumer =================== [CapSubscribe("place.order.qty.deducted")] public object DeductProductQty(JsonElement param) { var orderId = param.GetProperty("OrderId").GetInt32(); var productId = param.GetProperty("ProductId").GetInt32(); var qty = param.GetProperty("Qty").GetInt32(); //business logic return new { OrderId = orderId, IsSuccess = true }; } ``` -------------------------------- ### Register CAP Services Source: https://github.com/dotnetcore/cap/blob/master/docs/content/user-guide/en/cap/configuration.md Register CAP services by providing configuration options when adding CAP to the DI container. ```csharp services.AddCap(config => { // config.XXX }); ``` -------------------------------- ### Configure Vite Development Server Proxy Source: https://github.com/dotnetcore/cap/blob/master/src/DotNetCore.CAP.Dashboard/wwwroot/README.md Sets up the Vite development server to proxy API requests to the backend service. Update the 'target' to point to your backend API. ```javascript server: { proxy: { '^/cap/api': { target: 'http://localhost:5000', //backend changeOrigin: true } } } ``` -------------------------------- ### Configure Consul Discovery in CAP Source: https://github.com/dotnetcore/cap/blob/master/docs/content/user-guide/en/monitoring/consul.md This C# code snippet shows how to configure Consul discovery within the CAP service. Ensure Consul is running and accessible at the specified host and port. ```csharp services.AddCap(x => { x.UseMySql(Configuration.GetValue("ConnectionString")); x.UseRabbitMQ("localhost"); x.UseDashboard(); x.UseConsulDiscovery(_ => { _.DiscoveryServerHostName = "localhost"; _.DiscoveryServerPort = 8500; _.CurrentNodeHostName = Configuration.GetValue("ASPNETCORE_HOSTNAME"); _.CurrentNodePort = Configuration.GetValue("ASPNETCORE_PORT"); _.NodeId = Configuration.GetValue("NodeId"); _.NodeName = Configuration.GetValue("NodeName"); }); }); ``` -------------------------------- ### Enable Activity Listener for Non-Framework Scenarios Source: https://github.com/dotnetcore/cap/blob/master/docs/content/user-guide/en/monitoring/opentelemetry.md If not using a framework that automatically handles listeners (like ASP.NET Core), enable a custom Activity Listener to capture and process activity data. This is useful for debugging and understanding trace flow. ```csharp ActivitySource.AddActivityListener(new ActivityListener() { ShouldListenTo = _ => true, Sample = (ref ActivityCreationOptions _) => ActivitySamplingResult.AllData, ActivityStarted = activity => Console.WriteLine($"{activity.ParentId}:{activity.Id} - Start") , ActivityStopped = activity => Console.WriteLine($"{activity.ParentId}:{activity.Id} - Stop") }); ``` -------------------------------- ### Configure Custom Headers for RabbitMQ Source: https://github.com/dotnetcore/cap/blob/master/docs/content/user-guide/en/transport/rabbitmq.md Set custom headers for RabbitMQ messages when integrating with heterogeneous systems or management consoles. ```csharp x.UseRabbitMQ(aa => { aa.CustomHeadersBuilder = (msg, sp) => [ new(DotNetCore.CAP.Messages.Headers.MessageId, sp.GetRequiredService().NextId().ToString()), new(DotNetCore.CAP.Messages.Headers.MessageName, msg.RoutingKey) ]; }); ``` -------------------------------- ### Explicit Idempotence with Message Tracking Source: https://github.com/dotnetcore/cap/blob/master/docs/content/user-guide/en/cap/idempotence.md Demonstrates how to explicitly handle message redeliveries by tracking processed message IDs using an IMessageTracker. This approach requires a transactional data store for tracking. ```csharp readonly IMessageTracker _messageTracker; public SomeMessageHandler(IMessageTracker messageTracker) { _messageTracker = messageTracker; } [CapSubscribe] public async Task Handle(SomeMessage message) { if (await _messageTracker.HasProcessed(message.Id)) { return; } // Do the actual work here // ... // Record that this message has been processed await _messageTracker.MarkAsProcessed(message.Id); } ``` -------------------------------- ### Registering SNS Topics with CAP Source: https://github.com/dotnetcore/cap/blob/master/docs/content/user-guide/en/transport/aws-sqs.md Defines subscriber methods that CAP will register as SNS topics upon startup. Note the topic naming conventions used by CAP. ```csharp [CapSubscribe("sample.sns.foo")] public void TestFoo(DateTime value) { } [CapSubscribe("sample.sns.bar")] public void TestBar(DateTime value) { } ``` -------------------------------- ### Configuring CAP for Heterogeneous Systems with Azure Service Bus Source: https://github.com/dotnetcore/cap/blob/master/docs/content/user-guide/en/transport/azure-service-bus.md When listening to messages from an external system, add two mandatory headers for CAP compatibility: MessageId and MessageName. This ensures proper integration with CAP's messaging patterns. ```csharp c.UseAzureServiceBus(asb => { asb.ConnectionString = ... asb.CustomHeadersBuilder = (msg, sp) => [ new(DotNetCore.CAP.Messages.Headers.MessageId, sp.GetRequiredService().NextId().ToString()), new(DotNetCore.CAP.Messages.Headers.MessageName, msg.RoutingKey) ]; }); ``` -------------------------------- ### Publish Message with Extra Headers Source: https://github.com/dotnetcore/cap/blob/master/docs/content/user-guide/en/getting-started/quick-start.md Publish a message with custom headers by providing a dictionary of key-value pairs. ```csharp var header = new Dictionary() { ["my.header.first"] = "first", ["my.header.second"] = "second" }; capBus.Publish("test.show.time", DateTime.Now, header); ``` -------------------------------- ### Enable CAP Dashboard Source: https://github.com/dotnetcore/cap/blob/master/docs/content/user-guide/en/monitoring/dashboard.md Add this code to your configuration to enable the CAP Dashboard functionality. The Dashboard is only supported for ASP.NET Core applications. ```csharp services.AddCap(x => { // ... // Register Dashboard x.UseDashboard(); }); ``` -------------------------------- ### Add CAP Dashboard Standalone Source: https://github.com/dotnetcore/cap/blob/master/docs/content/user-guide/en/monitoring/kubernetes.md Configure the CAP dashboard to run standalone without CAP configuration. This allows the dashboard to be deployed as a separate Pod for data viewing. ```csharp services.AddCapDashboardStandalone(); ```