<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Kevin Patrick Boylan | .NET Software Engineer on Medium]]></title>
        <description><![CDATA[Stories by Kevin Patrick Boylan | .NET Software Engineer on Medium]]></description>
        <link>https://medium.com/@kevinpatrickboylan?source=rss-cdb3e200aa99------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ck1Avv8imtXIj6XzUfcVOQ.jpeg</url>
            <title>Stories by Kevin Patrick Boylan | .NET Software Engineer on Medium</title>
            <link>https://medium.com/@kevinpatrickboylan?source=rss-cdb3e200aa99------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 16:07:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kevinpatrickboylan/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Event-Driven Microservices with Azure Functions, Service Bus, and Minimal API]]></title>
            <link>https://medium.com/@kevinpatrickboylan/event-driven-microservices-with-azure-functions-service-bus-and-minimal-api-5b3a294e6b1d?source=rss-cdb3e200aa99------2</link>
            <guid isPermaLink="false">https://medium.com/p/5b3a294e6b1d</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[azure-functions]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[azure]]></category>
            <dc:creator><![CDATA[Kevin Patrick Boylan | .NET Software Engineer]]></dc:creator>
            <pubDate>Mon, 14 Jul 2025 15:43:12 GMT</pubDate>
            <atom:updated>2025-07-14T15:54:47.632Z</atom:updated>
            <content:encoded><![CDATA[<h3>1. Introduction: What is Microservice Architecture?</h3><p><strong>Microservice architecture</strong> is a design approach where a system is decomposed into a collection of small, independent services. Each service is responsible for a single business capability and can be developed, deployed, and scaled independently of the others.</p><p>Unlike <strong>monolithic applications</strong> — where all functionality lives in one large codebase — microservices promote separation of concerns. This allows teams to iterate faster, deploy services without affecting the whole system, and choose the most appropriate technologies for each part.</p><p>Some of the key characterstics of a microservice architecture:</p><p><strong>Autonomous and Decentralized</strong>: Each microservice is self-contained, with its own data and logic. It can be developed, deployed, and scaled independently.</p><p><strong>Resilience and Fault Tolerance</strong>: Failure in one service doesn’t bring down the whole system — especially when fault-handling strategies (like those provided by Polly) are in place.</p><p><strong>Loose Coupling and Scalability</strong>: Microservices interact through well-defined APIs or asynchronous messaging systems, reducing dependencies. Individual microservices can be scaled horizontally based on demand (e.g., scaling only the payment service during peak sales time periods).</p><p>In my case, I was looking at a <strong>.NET Core API</strong> controller project I developed, and wishing to start over with something smaller and more decoupled. The existing API definitely meets the definition of monolithic. Here are some views of my Solution Explorer:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/679/1*GOc2xzmMC94lCYlFGhQxgA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/643/1*yy9lWi6xfiC372tO6gyh7A.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/709/1*f_ly--AbG1uiYAGfklTMxQ.jpeg" /></figure><p>You can probably already recognize the <strong>Controller → Service (UseCase) → Repository</strong> pattern from the project structure. In the cases of creating new Materials and Products, the repository layer is responsible for inserting controller request payloads into a <strong>SQL Server</strong> database.</p><p>This is a common pattern and usually works without issues, but I started questioning this architecture for at least a few reasons.</p><p><strong>Scenario #1</strong>: The database is offline. My database resides in Azure. What if Azure is running maintenance tasks that take my database offline for a few minutes? If someone tries to add a new product during this period, the repository will raise a 500 error and there will be no persistent record of the request payload.</p><p><strong>Scenario #2</strong>: I need to make a small change to the material entity: for example, add a Country Code property. This requires recompiling the API, and if I’m using <strong>continuous integration</strong> (CI), it also means kicking off a new build in GitHub and a deployment to Azure. Just for adding one new class property.</p><p><strong>Scenario #3</strong>: I’d like to change the database server for storing and managing products from <strong>SQL Server</strong> to <strong>PostgresSQL</strong>. I can make this change easily enough in the API but I will be facing the same tasks I mentioned in Scenario #2. I would also need to <strong>smoke test</strong> pretty thoroughly too, to ensure the change doesn’t introduce knock-on effects elsewhere in the application.</p><p><strong>Scenario #4</strong>: I’d like to add a new service that will send email notifications to a user group when a new product is added to the database. Doing this will make the monolithic codebase grow again.</p><p>So I was envisioning a small and simple <strong>greenfield </strong>project, where I can leverage both Azure features and a decoupled, microservices approach to development. The goal is to eventually and permanently walk away from my current monolithic API.</p><p>In what follows, I’ll describe the steps I took and the stack I used to implement my example.</p><h3>2. Overview of the New Architecture</h3><ol><li><strong>Angular Front-End</strong>: A simple UI with a couple of data entry forms.</li><li><strong>.NET Core Minimal API</strong>: I wanted an alternative to .NET Core API for message publishing.</li><li><strong>Azure Portal</strong>: For this example, I took advantage of <strong>Azure Functions</strong>, <strong>Service Bus</strong>, and <strong>App Service</strong>.</li></ol><h3>3. Angular Front-End</h3><p>The front-end consists of two forms, one for adding new products, the other for adding new materials.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q78dWxRWzqqEhrfzFPP3Uw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KpfjCAQf2894estFc4Q7VA.jpeg" /></figure><p>In earlier versions of the front-end, these forms were posting <strong>JSON </strong>payloads to API Controller methods which insert the payload data into a <strong>SQL Server</strong> database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/459/1*RL6o4sIemZCS9F10N8rmUQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*vSE2_b6Ax2J-oTQ5q3f6Gw.jpeg" /></figure><p>But now I want to change the responsibility of the UI, to instead publish messages to an Azure Service Bus queue.</p><h3>4. Minimal API as the Message Publisher</h3><p>In my example, I wanted a lightweight and simpler approach to publishing messages from my front-end. The <strong>Model-View-Controller (MVC) </strong>version of API seemed overly complex for my new requirements, when I compared it to Minimal API:</p><p><strong>Structure</strong>: It follows a full MVC or layered architecture (Controllers, Startup.cs, Program.cs).</p><p><strong>Controllers</strong>: It uses *Controller* or *ControllerBase* with routing attributes.</p><p><strong>Dependency injection</strong>: Constructor injection in controllers and services can quickly grow in terms of code size and maintenance effort.</p><p>My <strong>Minimal API </strong>solution has two responsibilities: to publish material and product messages posted from the front-end UI. Another requirement for this project is to publish new product data to an email queue, which will be consumed by an application that sends emails based on the product data.</p><p>As you can see, the Solution Explorer has a much smaller and simpler structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/298/1*Ig0VW221sdJk6-GUV7kzLA.jpeg" /></figure><p>Notice there is no Controllers folder. With Minimal API, you can map Http routes (e.g. Post, Get, etc) in <strong>Program.cs</strong>. And the mappings are simpler and more concise than the equivalent structure of a MVC Controller. Here are my two route mappings for publishing products and materials.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/1*KYXg_iLnJLz9_rJL7_hIJg.jpeg" /></figure><p>When I run the project, the <strong>Swagger UI</strong> looks very similar to what we’d see with an API controller project:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A2LeUF6tEbg8Uv7YL-ZcMA.jpeg" /></figure><p>So this is a quick summary of some of the differences between Minimal API and API Controllers. I haven’t yet covered how my API actually publishes messages to Azure Service Bus. Looking at Program.cs again, you can see dependency injections registered for <strong>IAzureServiceBusSvc </strong>and <strong>AzureServiceBusSvc </strong>(for Material and Product types) and for <strong>IEmailServiceBusPublisher </strong>and <strong>EmailServiceBusPublisher</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*WXpT12gsaYqapzYpLiSHDQ.jpeg" /></figure><p><strong>IAzureServiceBusSvc </strong>has one method, <strong>PublishAsync</strong>. Because it expects a type, or <strong>T</strong>, parameter, it can handle both Material and Product objects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/541/1*8DCcCaHZU10GXpG3Uj4KWQ.jpeg" /></figure><p>The implementation of PublishAsync in <strong>AzureServiceBusSvc </strong>is pretty straightforward, with very little code required to push a message payload onto Azure Service Bus. By simply including <strong>using Azure.Messaging.ServiceBus</strong>, I have everything I need to publish messages with a minimal amount of code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/706/1*NE5_WzNhoB6G8nbNuHxsig.jpeg" /></figure><p>Since I want to publish new product data to an email queue, there is a conditional check on the queue name (i.e. is it the product queue). If the message goes to the product queue, a second message is created and published to the email queue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*k8kUmPNukOBWFf79WBzSsA.jpeg" /></figure><p>I have a helper method that conditionally retrieves the queue name from <strong>appsettings.json</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*4tMx1O00BClEeN9zv5OCMA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/345/1*GivM1AKPWUcCRimqpfwhXQ.jpeg" /></figure><h3>5. Azure Service Bus Queues</h3><h4>Create a Service Bus Namespace</h4><p>The first step to using <strong>Service Bus</strong> is creating a Service Bus namespace. My namespace is <strong>productionerp</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XA_vtJlzUgwKIkdNEaYrMw.jpeg" /></figure><p>After clicking the namespace name, I created three queues.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*nxMjwzaL48p5Joh9dCh69w.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G8WtbCY4ri9QlRnhozmBBg.jpeg" /></figure><p>You can think of the namespace <strong>productionerp </strong>as a logical grouping of queues.</p><h3>6. Azure Functions as Message Consumers</h3><p>Just to summarize the previous steps:<br>1. I have a Minimal API that publishes messages onto Azure service bus queues.<br>2. I have two Angular forms (Add Product and Add Material) that post form data to the Minimal API.<br>3. In Azure, I have three queues: <strong>material_queue</strong>, <strong>product_queue </strong>and <strong>email_queue</strong>.</p><p>I now have a process where product, material and email messages can be published to Azure queues. Now I need to implement <strong>message consumers</strong> which have the responsibility of detecting new messages on the queues and inserting them into a <strong>SQL Server</strong> database.</p><p>For this requirement, I created three <strong>Azure Functions</strong>.</p><h4>What are Azure Functions?</h4><p>Azure Functions is a<strong> serverless compute service</strong> that lets you run small pieces of code (“functions”) without managing infrastructure. It automatically scales and charges based on execution time, making it ideal for <strong>event-driven </strong>applications.</p><p>In the context of <strong>queue triggers</strong>— which is what I use in this example, Azure Functions can be configured to automatically execute when a new message arrives in a <strong>Service Bus queue</strong>. This makes it easy to build a reactive, decoupled system where components communicate through messaging.</p><p>A queue trigger is a specific type of event that executes an Azure Function. When you configure an Azure Function with a queue trigger (e.g., for Azure Service Bus queues), the function will automatically execute whenever a new message is added to that designated queue.</p><p>In my example, the function will detect the message, deserialize it to a <strong>C# entity</strong> and insert it into a database table.</p><h4>Project example: ProductQueueFunction</h4><p>To create this project in <strong>Visual Studio 2022,</strong> I selected <strong>Azure Functions</strong> from the Recent project templates list.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/1*Y6rnhEbu42P9PBZII7MssA.jpeg" /></figure><p>After entering a name for the project, I selected <strong>Queue trigger</strong> from the Function dropdown. You’ll see there are several options here, including <strong>RabbitMQ </strong>trigger.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*zBoSlGs8ozsDw5uQkEqlxQ.jpeg" /></figure><p>One very important field to note here is the <strong>Connection string setting name</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/1*GPu7zEhrPwDTSjeSX7MbnQ.jpeg" /></figure><p>The connection string for Azure service bus has a similar function to that of database connection strings. It contains the location of the service bus namespace and an identifier access key for authentication.</p><p>I have both my service bus and database connection strings stored in <strong>local.settings.json</strong>. If this is how you prefer to store these values, just make sure the file is in your <strong>.gitignore</strong>, to prevent it from getting pushed to your <strong>GitHub </strong>repository.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1fBlJRYW0-Wsfp1-czlSyQ.jpeg" /></figure><p>The structure of the project and code is quite simple and straightforward.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/265/1*eDRs0QzMTBnsl4ylpfh7jw.jpeg" /></figure><p>All of the features I need for the function is provided by the <strong>Microsoft.Azure.Functions.Worker </strong>NuGet package. I use the package in two places, <strong>Program.cs </strong>and <strong>QueueToDbFunction.cs</strong>.</p><p>Besides configuring the required Azure services, Program.cs also registers the dependency between my Repository interface and implementation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/507/1*2chVz-8qhNTqf7flXNhqzg.jpeg" /></figure><p>For this example, the repository has one simple responsibility: insert deserialized product messages into a <strong>SQL Server</strong> table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/1*gYdrZyrF33CeDiq7frVU2g.jpeg" /></figure><p>The consuming of published messages was implemented in <strong>QueueToDbFunction.cs</strong> with minimal code.</p><ol><li>A repository is instantiated via constructor injection.</li><li>The <strong>RunAsync </strong>method executes when a message is detected on the queue.</li><li>The name of the Azure queue and the service bus connection string name are specified in the <strong>ServiceBusTrigger </strong>attribute, which is an attribute of the message parameter.</li><li>The message is deserialized into a Product object which is passed to the repository method <strong>AddMaterialAsync</strong>.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*JD8QsUNls3xbJfjQqX-gsw.jpeg" /></figure><h3>7. Deploying and Configuring Functions in Azure</h3><p>After successfully testing the functions on my localhost, the next step was to deploy the three functions to Azure. This is quite a simple process in Azure and consists of these tasks:</p><ol><li>Create the functions in Azure.</li><li>Committing and pushing my function projects from localhost to GitHub.</li><li>Deploy from GitHub to the functions in Azure.</li></ol><h4>Create the functions in Azure</h4><p>Select <strong>Function App</strong> in the Azure portal, then select <strong>Create.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/1*9lwMNtn-biC3i9SeC0C1pw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/849/1*RRa1BVhRlr5US2sbNV4sqA.jpeg" /></figure><p>After completely these steps, I now have three functions in Azure, for consuming material messages, product messages and email messages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/1*Vc1PuhWaCbNKPJC6dgfpUg.jpeg" /></figure><h4>Pushing Functions to GitHub</h4><p>I committed and pushed my three function projects to GitHub after testing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*e_-xr5-H23HQ375007_-7A.jpeg" /></figure><h4>Deploy from GitHub to the functions in Azure</h4><p>Once I pushed all my function changes to GitHub, the next step was to go to each function in Azure and trigger a deployment from GitHub.</p><p>This is easily done by going to <strong>Deployment Center</strong>, on the Deployment menu. Just select your GitHub settings and repository, and Azure will trigger a deployment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cl9MzqKf-dTGgwUm6v6A5A.jpeg" /></figure><h3>8. Configuring Email in Azure Functions</h3><p>As I mentioned earlier, one of my requirements in this example is to generate emails that will go to a designated user or group of users when a new product message is published. Additional requirements for this example: the email platform has to be free of charge for my usage, and it has to be configurable and usable in Azure portal.</p><p>I chose the <strong>Twilio SendGrid</strong> API platform because it meets all my requirements. I won’t go into all the details of setting up SendGrid but I’ll mention that the most important part is generating an API key in SendGrid. This key has to be referenced for authentication purposes from both my localhost use of SendGrid’s API and within Azure portal.</p><h4>Project: EmailQueueFunction</h4><p>This Azure function project requires the <strong>SendGrid </strong>NuGet package. After I installed the package, I added the SendGrid API key to the project’s <strong>local.settings.json</strong>. Again, this file is in <strong>.gitignore</strong> to exclude it from GitHub.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*EKG1O4uHDzUwVKKbLwKSFg.jpeg" /></figure><p>When the function detects a new message on the email queue, a product object is created and a new email message is assembled with the product data. A <strong>SendGridClient</strong>,<strong> </strong>object sends the email.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mx7y4VO2DaTTkKQOxfW3Uw.jpeg" /></figure><p>Because I’m not pushing my <strong>local.settings.json</strong> to GitHub, the function has to be able to retrieve the SendGrid API key, once it is deployed to Azure. This is easily done in Azure by creating a new <strong>App setting</strong> for the Email function.</p><p>I navigated to the function in Azure, went to <strong>Settings → Environment variables </strong>and added a new setting <strong>SENDGRID_API_KEY</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RII1If14zf0Ilc-33tYk_g.jpeg" /></figure><p>And that completes my implementation and configuration. Now is a good time to test a full run from front-end to back-end.</p><h3>9. End-to-End Testing and Results</h3><p>I’m going to add a new Product (<strong>Loratadine</strong>, an allergy medication) through my Angular UI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KsGzBMZB-mR7taemyA7HMA.jpeg" /></figure><p>Then I need to confirm the following results:</p><ol><li>A new Product message was published by Minimal API to <strong>product_queue </strong>in Azure</li><li>A new Email message was published by Minimal API to <strong>email_queue </strong>in Azure.</li><li>A product record was inserted into SQL Server by Azure function <strong>product-queue-fn</strong>.</li><li>A new email was successfully delivered by Azure function <strong>email-queue-fn</strong>.</li></ol><p>For now, I have everything in Azure turned off. This is mainly because I want to minimize the costs I incur from month to month, but in this particular case, to confirm my new architecture is working correctly, I need to turn on features selectively so that I can confirm each step separately.</p><p>I’ll first start up the <strong>minapi-staging</strong> app and the product and email message queues. I’ll leave the functions in a stopped state because I want to verify that the messages are on the queues after I submit the Angular form: if the functions are running, we won’t see the messages because they are quickly processed.</p><p>After submitting the form, I went to the Queues dashboard and confirmed that a new message was published to both product and email queues.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oLHpvKibDokLsUPt6E_91Q.jpeg" /></figure><p>So far, so good. Let’s now take a look at the contents of each message.</p><p>The Product message:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*28vtYIMhwhLEjZ1A_IKKiw.jpeg" /></figure><p>The Email message:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nPu1QcEjtyyqMTOBwNYE-g.jpeg" /></figure><p>The message body of the email message will be used by the Azure email function to build and send an email.</p><p>So I’ve confirmed that the Minimal API successfully processed a POST from the Angular UI and published two nessages. Now I will start up the product and email functions in Azure. Remember these functions are message <strong>consumers</strong>: their role is to watch their queues and process any new messages found.</p><p>To demonstrate the decoupled structure of these functions — think <strong>single responsibility</strong> — I will start the product function first and leave the email function in a stopped state.</p><p>After starting up <strong>product-queue-fn</strong>, I checked the Products table in SQL Server to confirm that the product message is successfully consumed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*xVI0p1nz33BwqelZimIsQg.jpeg" /></figure><p>And because the email function hasn’t started yet, the email message remains on the queue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*PunbtCqS_98yEUbcWh3LJg.jpeg" /></figure><p>I’ll start function <strong>email-queue-fn</strong> now.</p><p>The email queue has no messages now, and an email was successfully created and delivered.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*cuGcRv3QHo7QzLsZtwFBKQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*61OdcEOJBPhd_-FvLBhAfA.jpeg" /></figure><h3>10. Summary of the Solution</h3><p>I went through a completely successful execution of an end-to-end test, with results hopefully demonstrating the power and benefits of microservice architecture. Since I covered quite a lot here, here is a summary of the process flow, just to recap:</p><p><strong><em>Angular UI</em></strong>: Initiates the flow by sending POST requests for Material and Product messages to the <strong>Minimal API</strong>.<br><strong><em>Minimal API</em></strong>: Hosted on Azure, receives requests and publishes messages to <strong>material_queue </strong>and <strong>product_queue</strong>.<br><strong><em>Azure Service Bus Queues</em></strong>:<br> <strong>material_queue</strong>: Triggers <strong>material-queue-fn</strong>.<br> <strong>product_queue</strong>: Triggers <strong>product-queue-fn</strong>.<br> <strong>email_queue</strong>: Triggered by <strong>product-queue-fn</strong>, feeds <strong>email-queue-fn</strong>.<br><strong><em>Azure Functions</em></strong>:<br> <strong>material-queue-fn</strong>: Reads from <strong>material_queue </strong>and inserts data into SQL Server.<br> <strong>product-queue-fn</strong>: Reads from <strong>product_queue</strong>, inserts data into SQL Server, and publishes to <strong>email_queue</strong>.<br> <strong>email-queue-fn</strong>: Reads from <strong>email_queue </strong>and sends emails via an Email Service.<br><strong><em>SQL Server</em></strong>: Stores data from <strong>material-queue-fn</strong> and <strong>product-queue-fn</strong>.<br><strong><em>Email Service</em></strong>: Receives and processes email requests from email-queue-fn.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HFxTIYlzxrOL9Xi47KCoKg.png" /></figure><h3>11. Future Improvements</h3><p>I wanted to provide a simple example to demonstrate the power of using <strong>Azure </strong>and <strong>Minimal API </strong>to implement a <strong>microservice architecture</strong>. But there’s plenty of room for improvement in this current implementation. There are at least three changes I’d like to make, sooner, rather than later.</p><ol><li>Refactor the Minimal API by applying a <strong>Unit of Work pattern</strong> to tie together the product and email message publishing into one transaction. Product and email publishing shoud either succeed together, or fail together.</li><li>Add <strong>Polly </strong>to the Minimal API for better resilience (e.g. retry logic, fallback actions, etc.). As part of this change, I’ll create new SQL Server tables to <strong>persist message data</strong> in cases where message publishing fails to puts messages onto Service Bus. I’ll then create new Azure Functions with the responsibility of monitoring the table for new records and <strong>re-publishing</strong> them as messages.</li><li>Create staging and production instances of the Azure Functions, and then implement GitHub workflow actions to manage deployments to these instances. I’d like these functions to work smoothly as part of a <strong>feature and release branch</strong> strategy.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5b3a294e6b1d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Azure AD Authentication in Angular and .NET Core API]]></title>
            <link>https://medium.com/@kevinpatrickboylan/implementing-azure-ad-authentication-in-angular-and-net-core-api-1da94b647546?source=rss-cdb3e200aa99------2</link>
            <guid isPermaLink="false">https://medium.com/p/1da94b647546</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[net-core]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Kevin Patrick Boylan | .NET Software Engineer]]></dc:creator>
            <pubDate>Tue, 01 Jul 2025 11:56:10 GMT</pubDate>
            <atom:updated>2025-07-01T11:56:10.614Z</atom:updated>
            <content:encoded><![CDATA[<h3>Implementing Azure AD Authentication in Angular and .NET Core API</h3><h3>1. Introduction: The Challenge of Modern Authentication</h3><p>As a developer interested in following best Azure practices, I recently took a look at securing my <strong>.NET Core API</strong> with <strong>Azure Active Directory</strong> (AD). I have experience over the years developing my own custom authentication patterns. In my case, these typically consisted of at least four components:</p><ol><li>A <strong>SQL Server database</strong> for storing user login data, such as username, password, email address, etc.</li><li>An <strong>API controller </strong>that authenticates a submitted login request by querying the database.</li><li>An <strong>API service layer</strong> that generates a <strong>JWT </strong>token and returns it to the client application.</li><li>The client application (in my case an <strong>Angular </strong>UI) stores the JWT in a local cache.</li></ol><p>As a stand-alone solution, this design worked pretty well. But I wanted to implement an alternative solution, one that is tightly integrated with Azure AD. In what follows, I’ll show you the steps I went through to integrate <strong>Azure</strong>, <strong>Angular </strong>and <strong>.NET API</strong>.</p><h3>2. The Azure and .NET Core Ecosystem</h3><h4>Azure AD</h4><p>Azure AD is crucially important for applying the <strong>SaaS (Software as a Service)</strong> concept to application security. With Azure AD, I am simply <strong>using </strong>its features: e.g. I don’t have to install <strong>Active Directory</strong>, manage virtual machines, server patches, etc.</p><p>There are also aspects of Azure AD that can be considered examples of <strong>PaaS (Platform as a Service)</strong>. A good example, that we’ll look at later, is the availablity of the <strong>MSAL (Microsoft Authentication Library)</strong> modules in Angular that allow developers to integrate their Angular applications with Azure AD.</p><p>There are several powerful features offered by Azure AD when implementing secure connections between client applications and APIs.</p><ol><li><strong>OAuth 2.0/OpenID Connect</strong> support: Azure AD can issue secure tokens for an Angular app, which can be sent to an API for authentication.</li><li><strong>[Authorize]</strong> attribute enforcement: .NET Core API can validate these tokens, ensuring only authenticated users can access protected controllers.</li><li><strong>Single Sign-On (SSO)</strong>: Users can log in once and access multiple apps (e.g., Angular and API) without re-authenticating.</li><li><strong>Enterprise-grade security</strong>: Built-in support for Multi-factor Authentication (MFA), conditional access, and integration with Microsoft 365/Entra ID.</li></ol><p>In summary: <strong>Azure AD</strong> enables secure, token-based authentication and authorization between an Angular front-end and .NET back-end with <strong>minimal custom code</strong>.</p><h4>Angular UI</h4><p><strong>Materials_UI </strong>is my user-facing application. In my simple example, there is a data grid populated by a Core API controller.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n2IPKDnp_PyHBAXfNiBs3w.jpeg" /></figure><p>Before I made any changes, the UI was requesting and loading data from the API without any authentication required. The controller endpoint was unprotected and nothing was persisted in the UI in terms of authentication objects such as tokens. This was a purely <strong>stateless </strong>request/response transaction, without any kind of intervening authentication.</p><p>Not only is this far from ideal, it is unrealistic: nowadays both third-party and internal APIs almost always require some form of oAuth authentication scheme. I have developed Angular UIs that persist authentication tokens but for this approach to work, I had to write quite a bit of custom <strong>TypeScript </strong>logic to prevent unauthenticated users from accessing certain routes in the Angular UI.</p><p>One downside to this approach is that my API controller still remained unprotected. With this less than ideal solution, I was protecting, or <strong>guarding</strong>, UI routes using logic <strong>inside </strong>the UI, but the controller endpoint remained accessible, without any access to authentication tokens.</p><h4>.NET Core API</h4><p>For this example, I have a simple API <strong>MaterialAPI_Azure </strong>with one controller and one responsibility: to retrieve and return a list of materials typically used in lifescience manufacturing operations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*og1Nt7W69DqHCvASV_fKKg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vbHle3jZgfV7GKIFjvhMkA.jpeg" /></figure><p>As we’ll soon see, we can easily protect the controller endpoint once we have completed some configuration tasks in Azure AD.</p><h3>3. App Registrations in Azure Portal</h3><p>To integrate my front-end and back-end with Azure AD, I created two <strong>App registrations</strong> by going to Azure Active Directory in the portal, then to App registrations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HvdBlGL3EJyxIT7SaTYy9Q.jpeg" /></figure><p>The registrations are named <strong>AngularUI</strong> and <strong>MaterialAPI</strong>. In this security scenario, each application requires an app registration. AngularUI will integrate with my front-end, while MaterialAPI will ensure protection of my API endpoint.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5d27A8NyoMspFzaajsSmfQ.jpeg" /></figure><p>Let’s go through the configuration properties of each registration.</p><h4>MaterialAPI</h4><p>There are two important registration properties that need to be specified in the Angular front-end. The <strong>Application</strong>, or <strong>client</strong>, <strong>ID </strong>is the unique identifier assigned to the registration. This key is referenced in the front-end TypeScript and is what connects the front-end to the Azure registration.</p><p>The <strong>Directory</strong>, or <strong>tenant</strong>, <strong>ID </strong>is the unique identifier of the Azure directory where our app registrations are located. You can think of the tenant as logically similar to a file directory on disk. The tenant id must also be specified in the front-end code because, like directories and files on disk, both the tenant and client IDs form a logical path that Azure uses to locate the registration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/994/1*Na7x7P0D7V9rckqKi-fucA.jpeg" /></figure><p>The next step is to further configure MaterialAPI to actually protect my API endpoint. On the MaterialAPI <strong>Overview</strong>, I went to <strong>Expose an API</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*cSZPnDKIe_pCIT3E-w-37A.jpeg" /></figure><p>A few things to note here. First, notice the first field, Application ID URI and its value: api://2740e754-a106–45e1–8d32-d1b01042f761.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hsn9njnnjEXIJbfDTaYMYQ.jpeg" /></figure><p>The value is the <strong>client ID</strong> of the app registration. What the URI structure means is: there is an API somewhere and this identifier identifies it. In other words, the URI is the link that will connect my API to this registration.</p><p>In the previous screenshot, note the <strong>Scopes </strong>section. When exposing an API, there is a useful option for creating custom scopes. A scope allows one to fine-tune the access levels of the exposed API. In my example, I created a scope named <strong>Access_as_User</strong>. The scope name is then appended to the application URI: api://2740e754-a106–45e1–8d32-d1b01042f761/Access_as_User.</p><p>In a real-world scenario, I could create several scopes under a registration, allowing me to control access to different controllers in an API depending on factors such as user groups: e.g. customer service, administrators, factory operators, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pqvs8kS7dUBS6D6g_Roh4w.jpeg" /></figure><p>The MaterialAPI app registration is now complete.</p><h4>AngularUI</h4><p>Notice that the AngularUI registration has the same tenant ID as the MaterialAPI registration. As I mentioned earlier, this is how Azure AD logically groups app registrations together.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rYfSBhASygQap3Opg7v8nA.jpeg" /></figure><p>Because my front-end is a client requiring access to my API, there is no need for a scoped application URI, as was required with the MaterialAPI registration.</p><p>There are, though, a couple more steps required for completing configuration of the AngularUI registration. Under <strong>Overview</strong>, I went to <strong>Authentication</strong>. Then, under <strong>Platform configurations</strong>, I went to <strong>Add a platform</strong>.</p><p>Here I selected <strong>Single-page application</strong>, since my front-end is built with Angular. You would select the same option if your front-end was built with <strong>React </strong>or <strong>Vue</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X7FkZhtT0vJsyhzyghox2g.jpeg" /></figure><p>For configuration, there is just one field to fill in. The <strong>Redirect URI</strong> is very important here, because it tells Azure where to redirect the front-end after successful authentication in AD.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/599/1*X1XzBNjfvwYi8IDFRpTGxA.jpeg" /></figure><p>In my case, the redirect URI is <a href="http://localhost:4200/">http://localhost:4200</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*vcGXEuIyP7XRgzfjhj6VnA.jpeg" /></figure><p>The final step for AngularUI configuration is linking it to the MaterialAPI registration. Under <strong>Overview</strong>, I went to <strong>API permission</strong>, then <strong>Add a permission</strong>. On the <strong>Request API permissions</strong> screen, I selected <strong>MaterialAPI </strong>from the <strong>APIs my organization uses</strong> tab:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/847/1*MKtyozJKYjzw9ERlaMpK3A.jpeg" /></figure><p>I then selected <strong>Delegated permissions</strong> and clicked <strong>Add permissions</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*TK2MBexr89SujiJX56AUBw.jpeg" /></figure><p>Now my app registration is complete, and my Angular front-end and API back-end are now linked for authentication in Azure AD.</p><h3>4. Updating the Angular Front-end</h3><p>The first step for connecting Angular to Azure AD is to install the <strong>MSAL (Microsoft Authentication Library)</strong> modules:</p><p>npm install <a href="http://twitter.com/azure/msal-browser">@azure/msal-browser</a><br>npm install <a href="http://twitter.com/azure/msal-angular">@azure/msal-angular</a></p><h4>MSAL Set-up in app.module.ts</h4><p>These are the imports I added to app.module.ts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/855/1*atZP23UymIAzPk5loaWijw.jpeg" /></figure><p>In <a href="http://twitter.com/NgModule"><strong>@NgModule</strong></a>, I added <strong>MsalModule </strong>to the imports section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*0f6NHD43l1JGNcwt0KYBXQ.jpeg" /></figure><p>Under <strong>providers</strong>, I added the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/411/1*6jShtg3M23Vzeve6DTb8XQ.jpeg" /></figure><p>In my app.module.ts, there are four methods required for <strong>MSAL </strong>to function correctly. The first, <strong>initializeMsal</strong>, is critical because it initializes the <strong>MsalService</strong>, making it available to the Angular application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/553/1*s1aU2uHJqQNHweui2aRcRQ.jpeg" /></figure><p><strong>MSALInstanceFactory()</strong> is responsible for returning a <strong>PublicClientApplication </strong>object. Hopefully some of the property values will look familiar to you:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/757/1*rispjq2WrbtcmdPm4GGTcA.jpeg" /></figure><p>Because it returns a PublicClientApplication, it makes sense that the clientId value is the <strong>Azure client ID</strong> of the AngularUI <strong>app registration</strong> in Azure. Take a closer look at the value of <strong>authority </strong>and you’ll notice that the Azure <strong>tenant ID</strong> is appended to <a href="https://login.microsoftonline.com/">https://login.microsoftonline.com</a>.</p><p>The <strong>redirectUrl </strong>was also configured in the AngularUI registration. For security reasons, the redirectUrl specified in the front-end <strong>must match</strong> <strong>the RedirectURI</strong> in Azure AD.</p><p>There is a <strong>MSALInterceptorConfigFactory() </strong>method, which has the responsibility of <strong>intercepting </strong>API requests to validate the endpoint URL before sending the request to a controller. My localhost API has the URL <a href="https://localhost:7034/api">https://localhost:7034/api</a>. To protect any controller that begins with this URL, it must be specified under <strong>protectedResourceMap</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/1*nk52NPadtTIlec5uxXM7dg.jpeg" /></figure><p><strong>This method is critical</strong>. When a user is logged in, a bearer token is added to <strong>localStorage </strong>(e.g. the cache). When the <strong>interceptor </strong>checks the cache and finds a token, it add the token to the <strong>Authorization header</strong> of the Http request. In this scenario, the protected API endpoint can be accessed.</p><p>Finally, there is the <strong>MSALGuardConfigFactory()</strong> method. The <strong>scopes </strong>value, if you recall, was configured when I created the MaterialAPI app registration. The value in Angular <strong>must match</strong> the value in Azure AD, otherwise a request to the API controller will result in a <strong>401, Unauthorized</strong> exception.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/607/1*e9Ck1V6HNU7kUPFfxw2P8Q.jpeg" /></figure><p>To summarize the purpose of the last two methods:</p><ol><li><strong>MSALInterceptorConfigFactory() </strong>looks for an authentication token and adds it to the API request header.<br>2. <strong>MSALGuardConfigFactory()</strong> ensures there is a match between the MaterialAPI URI scope defined in Azure AD and the value set under <strong>scopes:</strong> in MSALGuardConfigFactory().</li></ol><h4>AppComponent Logic</h4><p>In <strong>app.component.ts</strong>, I first added the required imports for MSAL:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*vtxk2_q4jT8N1qqV7JobaA.jpeg" /></figure><p>The AppComponent constructor injects <strong>MsalService </strong>and <strong>MsalBroadcastService</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/1*0EQjrATFRC5bcwxBGj3pmw.jpeg" /></figure><p>Two main functions of the AppComponent are to:</p><ol><li>Subscribe to MSAL events to detect user-initiated login and logout events.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/991/1*kl75vR-EjZsDHrELGBSBaw.jpeg" /></figure><p>2. Subscribe to interaction status changes. For example, if a user session times out, we want Azure AD to initiate a new login (e.g. at <a href="https://login.microsoftonline.com/">https://login.microsoftonline.com</a>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/1*bBM6hAS9GX_D992fBscqkw.jpeg" /></figure><h3>5. Authorizing API Calls</h3><p>This was actually the easy part. In my <strong>.NET Core API</strong>, I simply added the <strong>[Authorize]</strong> attribute to my controller method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*RkYA9Uh87qWBoC8VVbtvvw.jpeg" /></figure><p>For <strong>Authorize </strong>to do its job, the API has to verify these things:</p><ol><li>The request has a <strong>bearer token</strong> in the <strong>Authorization header</strong>.<br>2. The bearer token contains the following <strong>claims</strong>: <br> <strong>tid </strong>(Tenant ID): my Azure AD Tenant ID.<br> <strong>aud </strong>(Audience): the Client ID of my MaterialAPI app registration.</li></ol><p>I just needed to do two more things:</p><ol><li>Add an appSettings.json setting:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/1*fITjrAMgmXf5BCFUW8rKGQ.jpeg" /></figure><p>2. Update <strong>Program.cs</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/523/1*vQpZjNPyFspPba_QhWEM7Q.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/861/1*won7ENT1uneZuuiJqtAQ9A.jpeg" /></figure><h3>6. Time to Test: A Few Test Scenarios</h3><p>I will now go through a quick test, where I will:</p><ol><li>Login to <a href="https://login.microsoftonline.com/">https://login.microsoftonline.com</a> when I visit <a href="http://localhost:4200/">http://localhost:4200</a>. The Microsoft login form is presented when I try to load my Angular UI because of the MSAL configuration I added to app.module.ts and app.component.ts.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/465/1*Kr5i5uD2pmd8z2luYfX2Gg.jpeg" /></figure><p>If we take a closer look at the login URL’s query string, we can note some interesting and critical values contained in the string. I’ve highlighted two.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F1uNCNJUfw8JJPeoQX4K1A.jpeg" /></figure><p>The first value, which immediately follows “<a href="https://login.microsoftonline.com/">https://login.microsoftonline.com</a>&quot; is my <strong>Azure tenant ID</strong>. The tenant, if you recall, is the logical location in Azure AD of my app registrations, AngularUI and MaterialAPI.</p><p>The second value of the <strong>client_id </strong>query parameter is the client, or application, id of the AngularUI app registration.</p><p>This gives us a bit of insight into what happens after I log out of my Angular UI. When I try to return to <a href="http://localhost:4200/">http://localhost:4200</a>, I’m redirected to Microsoft’s login page with the query string populated with all the parameter values required by Azure AD for authentication.</p><p>2. After logging in, I am now able to view the materials list page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rqI9j96d0VfWLAWoaNGJ9w.jpeg" /></figure><p>I added a few <strong>console.log</strong> lines to the Angular UI to log some of the important MSAL functions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/445/1*TJK9WpJ2tAvxHW0mA6Nl-A.jpeg" /></figure><p>So far, so good. But now I want to intentionally <strong>break </strong>the functionality. Sometimes breaking things on purpose helps my understanding and also gives me confidence that my code is working correctly.</p><p>In this case, I’m going to change the <strong>clientId </strong>in the <strong>MSALInstanceFactory()</strong> method to an invalid one. I added “XYZ” to the end, saved and reloaded the UI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/735/1*iLhpXiU710qEjaI8EWHbdQ.jpeg" /></figure><p>After trying to reload the UI, I receive this message from Azure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/1*F4LUQXwx8ysngR8TCZ4lbw.jpeg" /></figure><p>A very clear and straightforward message. After adding “XYZ” to the <strong>clientId </strong>and reloading the UI, a new request was sent to Microsoft Login with the <strong>non-existent</strong> clientId.</p><p>I’ll revert the change now and then introduce another bug. This time I’m going to change the base API <strong>endpoint URL</strong> in the <strong>MSALInterceptorConfigFactory()</strong> method to an incorrect one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*2kmREdk0fThtIChOz9AtOg.jpeg" /></figure><p>When I save the change and reload the UI, I see the following error in the browser console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l7NHYnRZuvAVY-CoVwuNRg.jpeg" /></figure><p><strong>401 </strong>is the Http error code for <strong>Unauthorized</strong>. By changing the API URL in app.module.ts, I was able to trigger the error because of a mismatch between the URL in Angular and the (correct) URL of the API endpoint. Because of the mismatch, the <strong>[Authorize]</strong> attribute on the Materials controller raised a <strong>401 error.</strong></p><h3>7. Summary of the Process Flow</h3><p>I covered quite a bit here, so let me give a quick summary of everything covered so far:</p><p><strong><em>User visits Angular UI</em></strong>: The Angular app loads.</p><p><strong><em>Login check</em></strong>: The AppComponent (via MsalBroadcastService and inProgress$ observable) detects no active logged-in user.</p><p><strong><em>Initiate login</em></strong>: The Angular app calls msalService.loginRedirect().</p><p><strong><em>Redirect to Azure AD</em></strong>: The browser is redirected to Azure AD’s login page.</p><p><strong><em>User logs in</em></strong>: User enters credentials and authenticates with Azure AD.</p><p><strong><em>Azure AD issues tokens</em></strong>: Azure AD verifies the user, sees the request is from AngularUI asking for MaterialAPI access, and issues an ID Token and an Access Token for MaterialAPI.</p><p><strong><em>Redirect back to Angular UI</em></strong>: Azure AD redirects the browser back to <a href="http://localhost:4200/">http://localhost:4200</a> with the tokens in the URL fragment.</p><p><strong><em>MSAL processes redirect</em></strong>: The Angular app’s APP_INITIALIZER and MsalRedirectComponent (or handleRedirectObservable) process the URL, extracting and caching the tokens. MSAL sets the active account.</p><p><strong><em>Angular UI makes API call</em></strong>: User interacts with the UI, triggering an HTTP request to <a href="https://localhost:7034/api/Material/active">https://localhost:7034/api/Material/active</a>.</p><p><strong><em>MsalInterceptor attaches token</em></strong>: The MsalInterceptor automatically adds the cached MaterialAPI Access Token to the request’s Authorization: Bearer header.</p><p><strong><em>Browser sends request</em></strong>: The browser sends the request.</p><p><strong><em>.NET API validates token</em></strong>: MaterialAPI receives the request. It extracts the Access Token, sends it to Azure AD (or uses cached keys) to validate its signature, expiry, issuer (my Tenant ID), audience (itself, MaterialAPI’s Client ID), and checks if the required Access_as_User scope is present.</p><p><strong><em>API responds</em></strong>: If the token is valid, the API processes the request and sends the data back to the Angular UI. If invalid, it returns an unauthorized error.</p><h3>8. Conclusion</h3><p>By integrating <strong>Azure Active Directory (Azure AD)</strong> with an <strong>Angular</strong> front-end and <strong>.NET API </strong>back-end, I quickly implemented a robust and scaleable solution for modern application security. This powerful combination centralizes identity management, leveraging Azure AD’s enterprise-grade capabilities for authentication and authorization. Developers like myself benefit from simplified security implementation, as much of the complex identity logic is offloaded to Microsoft’s trusted cloud service (i.e. SaaS), reducing the pain and burden of managing user credentials and access policies within the application itself.</p><p>The benefits extend beyond simple code. By utilizing Azure AD, applications gain enhanced security through features like <strong>multi-factor authentication</strong> (MFA), <strong>conditional access</strong>, and <strong>single sign-on</strong> (SSO), providing a seamless and secure user experience across various services. This approach fosters a more secure ecosystem, reduces the risk of security vulnerabilities inherent in custom authentication systems, and ensures compliance with industry standards. Ultimately, integrating Azure AD empowers developers to <strong>focus on core business logic</strong> while building highly secure, scaleable, and user-friendly applications with Angular and .NET APIs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1da94b647546" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multi-Tenant Feature Flags in .NET Core and Angular with Azure App Configuration]]></title>
            <link>https://medium.com/@kevinpatrickboylan/multi-tenant-feature-flags-in-net-core-and-angular-with-azure-app-configuration-cd5e17c7b3a0?source=rss-cdb3e200aa99------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd5e17c7b3a0</guid>
            <category><![CDATA[feature-flags]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[net-core]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Kevin Patrick Boylan | .NET Software Engineer]]></dc:creator>
            <pubDate>Sun, 15 Jun 2025 14:43:09 GMT</pubDate>
            <atom:updated>2025-06-15T14:43:09.770Z</atom:updated>
            <content:encoded><![CDATA[<h3>Multi-Tenant Feature Flags in .NET Core and Angular with Azure App Configuration</h3><h3>What is a Feature Flag?</h3><p>A <strong>feature flag</strong> (also known as a feature toggle, feature switch, or feature flipper) is a software development technique that allows you to turn specific functionalities of an application on or off dynamically, without modifying the source code or requiring a new deployment.</p><p>You can think of it as a remote control for your software. Instead of deploying an entirely new version of your application every time you want to enable or disable a feature, you can use a feature flag to control its visibility and behavior at runtime. This is typically achieved through conditional statements (e.g., if-else logic) in the code, where the execution path depends on the current state of the feature flag.</p><p><strong><em>Key aspects and benefits of feature flags include</em></strong>:</p><p><strong>Decoupling deployment from release</strong>: You can deploy new code with features “turned off” (hidden from users) and then release them selectively when ready, allowing for continuous integration and continuous delivery (CI/CD).</p><p><strong>Controlled rollouts</strong>: Introduce new features to a small subset of users (e.g., internal testers, beta users, a percentage of the user base) before a full public release. This reduces risk and allows for gathering feedback and identifying issues early.</p><p><strong>A/B testing and experimentation</strong>: Easily test different versions of a feature with different user groups to analyze their impact and make data-driven decisions.</p><p><strong>Kill switches</strong>: Quickly disable a problematic feature in production if it causes unexpected issues, without needing to roll back an entire deployment. This enhances application stability and reliability.</p><p><strong>Personalization</strong>: Tailor the user experience by enabling or disabling features based on user roles, subscriptions, geographic location, or other attributes.</p><p><strong>Reduced risk in migrations</strong>: Gradually migrate users to new infrastructure or platforms by enabling the new system for small groups while the old one remains active for others.</p><p>In essence, feature flags provide a powerful mechanism for managing the lifecycle of features, enabling greater agility, control, and safety in software development and delivery.</p><h3>My Scenario</h3><p>In my example, I have an <strong>Angular</strong> UI that simulates a simple <strong>ERP </strong>(Enterprise Resource Planning) system that allows lifescience manufacturers to manage basic ERP operations such as adding and editing users, products and materials.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OSQ2fF4HhRG_Bi106e6vVg.jpeg" /></figure><p>Now imagine there is a loyal customer who has been using my ERP for a few years. As a general rule, my ERP is sold as “working out of the box”, without any need for customizations.</p><p>But my customer has a pretty urgent requirement: to give some of its users more visibility into real-time manufacturing processes. One process involves sensor hardware that measures and records data points such as room temperature and humidity values. This data is critical for alerting factory operators if there is any deviation from normal temperature and humidity ranges during manufacturing.</p><p>I don’t want to lose this customer. I also believe that adding this new functionality would be a fantastic enhancement to the ERP and potentially generate future sales and new customers.</p><p>So what I need for now is a solution where my valued customer receives its requested feature but my other customers don’t face any risks that come with the implementation of the feature.</p><p>When my valued customer receives the new feature, its users will have new options in the navigation menu.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/979/1*qV0CBCGOiP_5Tcsvi6gKJw.jpeg" /></figure><p>Users will be able to view room temperature data:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LuPIMUTSsHFY2LjcxSnQ4w.jpeg" /></figure><p>And they will be able to view room humidity data:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NZxAYUdoaXMBQXQcLpVR2A.jpeg" /></figure><p>For other customers, Rooms will inaccessible and invisible:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8fd69t6gJ9jYT_uGzoCiKQ.jpeg" /></figure><p>In what follows, I’ll go through my back-end configuration that allows for different groups of users having access to different sets of features.</p><h3>What is Multi-Tenant Architecture?</h3><p>In <strong>multi-tenant architecture</strong> (MTA), a single instance of a software application and its underlying infrastructure serves multiple distinct groups of users, known as <strong>tenants</strong>. Each tenant operates as an isolated entity, with its own specific data, configurations, and user management, yet <strong>they all share the same application code and database schema</strong>.</p><p>This model offers important benefits such as reduced operational costs, simplified maintenance, and efficient resource utilization, as the provider doesn’t need to deploy and manage separate instances for each customer. It’s a common approach in <strong>Software-as-a-Service</strong> (SaaS) offerings where scalability and cost-effectiveness are critical.</p><h3>Technology Stack Overview</h3><p>My stack for this example consists of the following:<br>1. An Angular UI, described earlier.<br>2. Microsoft SQL Server<br>3. Azure Portal<br>4. .NET Core Web API</p><h4>Microsoft SQL Server</h4><p>To implement my very simple example of MTA, I made the following changes in my database.</p><p>I created a Tenants table to store tenants, or customers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/441/1*dF7MpCSVCy-QdJcZxRweBQ.jpeg" /></figure><p>In this example, Aurexa Biotech is the customer who will receive the new Rooms feature.</p><p>Next step was adding a TenantID column to my Users table and linking Aurexa Biotech to the user kboylan.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IyX_ZJVd5lVvENDxaEnofA.jpeg" /></figure><p>I then created a <strong>FeatureFlags </strong>table for storing features, and a <strong>FeatureFlagTenant </strong>table to link feature flags and tenants.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*AcQnJnPCxhSVj3ObvuIzrg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/193/1*NQkc-Hv4jrsogZI5TTaGAA.jpeg" /></figure><h4>Azure Portal and App Configuration</h4><p>First, I created a new <strong>Azure App Configuration</strong> named KPB-AppConfig:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/739/1*8psoXa8n37iLxQwNPLm4cg.jpeg" /></figure><p>I then added a new feature flag <strong>RoomsFeature</strong>, in the Feature manager section under Operations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w8PQ_euyeOr70ymTY54flw.jpeg" /></figure><p>Next, I specified the target group for the feature. To edit the feature flag, scroll down to Microsoft.Targeting and click Edit:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a96wmVGpYkROSD65_sVEJg.jpeg" /></figure><p>Under <strong>Include Groups</strong>, I added Aurexa Biotech, the tenant who will have access to the Rooms feature. For this scenario, I want all Aurexa users to have access, so I set the Percentage to 100.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D5opGO_xUW8J1WqqwYjXLQ.jpeg" /></figure><p>And that’s everything I had to do in Azure.</p><h4>The Back-end API</h4><p>I added the <strong>Microsoft.FeatureManagement.AspNetCore</strong> package to my project, and then updated <strong>Program.cs</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BEeK7ENXMuA3rXsPlXUd-w.jpeg" /></figure><p>Almost all of the functionality I need from Azure is handled in Program.cs. This is where I initialize the Azure connection string and open a connection to Azure to retrieve the feature flag configuration data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*0Lgj2KWD7jRxWZoWNLnxqA.jpeg" /></figure><p>For the sake of simplicity, I stored the connection string in <strong>appSettings.json</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oz7Ur2gckfdy4jI39_b0_Q.jpeg" /></figure><p>In a production setting, this would be poor practice of course. In fact, nowadays source repositories like GitHub won’t even, by default, allow you to push files that contain secrets. One real-life and secure way to configure the connection string is to use environmental variables created and stored in Azure. But that’s a topic for another day.</p><p>Going back to my Program.cs, here is where the Azure App Config is read:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*57GlmmWtEaPVH49tXHhAIg.jpeg" /></figure><p>When I run the API solution, we can see the output that was retrieved from Azure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sR-tPWobgsrUTonuKG2CdA.jpeg" /></figure><h4>Connecting the Front-end and Back-end</h4><p>So let me now summarize what I need to happen in the front-end UI.</p><p>1. When a user logs in, the back-end API will validate her login credentials, check the database for any links between her account and features and return a <strong>JWT token</strong> that contains feature flags if her tenant is linked to flags.</p><p>2. Once she is logged in, the front-end will store in cache any feature flags linked to her account. If the Rooms feature is returned from the API, she will see and have access to Rooms. Otherwise she will not.</p><p>Returning to the back-end, here is the controller method for querying feature flags during login. It first check the <strong>HttpContext </strong>for the logged in user’s TenantId. The HttpContext is written to with this data when the user first logs in.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*VuLDM1eBagdXGiHxZgaJ4g.jpeg" /></figure><p>This is the service method called by the controller.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/769/1*b2Pjg80dUc2OltuycgwgpQ.jpeg" /></figure><p>The code highlighted in red requires the Microsoft.FeatureManagement namespace.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/861/1*jj4YHuAauYkL7b2FDg8b0Q.jpeg" /></figure><p>Let me quickly unpack what happens when this code executes. I’ve already described how the initializing of the <strong>Azure App Configuration</strong> occurs in Program.cs. After that, only one line of code is required to check if a feature name exists in Azure!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/769/1*b2Pjg80dUc2OltuycgwgpQ.jpeg" /></figure><p>Now I’ll take you through my <strong>Angular </strong>UI and show you how it integrates with the back-end API to use feature flags.</p><p>The first step was creating a new FeatureFlag service component with three methods:</p><ol><li>getFeatureFlags</li><li>isFeatureEnabled</li><li>clearFlags</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/927/1*7M5ed2saRn95uencLDv4eQ.jpeg" /></figure><p>There is an existing login component:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/420/1*j9IKqcABz1m3GP4HZoU8Ww.jpeg" /></figure><p>The next step was to update the login component with calls to the new FeatureFlag service component methods:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/689/1*nQ94FuqYxJx2bVMwqAGfsg.jpeg" /></figure><p>Going back to the FeatureFlag component, here’s a quick summary of the logic. First, the service checks the browser’s <strong>localStorage </strong>for featureFlags and loads them into a cache.</p><p>If localStorage is empty, then a call is made to the FeatureFlag API. In this case, I <strong>console.log</strong> the feature flags, which we’ll see soon.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/943/1*HlJQnPNDC7SCrxh6a1eOmw.jpeg" /></figure><p>The final step was implementing <strong>toggling logic</strong> to hide or display the Rooms section of the navigation menu. Here is the navigation html.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/1*ZhDsa4zoRRGAOi8bFLP7Iw.jpeg" /></figure><p>The <strong>showRoomsFeature </strong>property is a boolean, checked each time the navigation menu loads. When true, the Rooms menu is displayed, otherwise it is hidden.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/979/1*biZJToNmFBO9J3cMqYrgjg.jpeg" /></figure><p>I tested this by logging in with two users. One (kboylan) belongs to Aurexa Biotech, a tenant with access to the Rooms feature. The other user (fsmith) belongs to NovaGenix Pharmaceuticals, which does not have access to this feature.</p><p>When I log in as <strong>kboylan</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/420/1*j9IKqcABz1m3GP4HZoU8Ww.jpeg" /></figure><p>I have access to Rooms. And we can see the feature data for Rooms returned from the API in the console output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/1*t2S0aCCu5RPq5I4RM4QNTg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/491/1*l6glsF6L280YVSA4O6NVgw.jpeg" /></figure><p>For my last test, I logged in as <strong>fsmith</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/1*cPfiFDGMh838pWcyxf1sFQ.jpeg" /></figure><p>The Rooms feature is not available, and we see no feature flag data in the browser console. This is exactly the result I was expecting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*Ioh4rfn3zxl85cJTeaeauw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/541/1*9yUJ8AZl9G0sZew1wMhTwQ.jpeg" /></figure><h3>Conclusion</h3><p>By integrating Azure App Configuration and feature flags into a multi-tenant .NET Core architecture, I was able to deliver a high-impact feature to a specific customer without disrupting the experience of other customers.</p><p>The approach I reviewed here not only preserved stability across tenants, but also gave me the flexibility to validate new functionality in a controlled way. As a result, with my fictional example, I met an urgent business need, strengthened a key customer relationship, and laid the groundwork for scalable, targeted feature rollouts in the future.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd5e17c7b3a0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Resilient Microservices with .NET Core, Polly, and RabbitMQ]]></title>
            <link>https://medium.com/@kevinpatrickboylan/building-resilient-microservices-with-net-core-polly-and-rabbitmq-f11fb83d31e0?source=rss-cdb3e200aa99------2</link>
            <guid isPermaLink="false">https://medium.com/p/f11fb83d31e0</guid>
            <category><![CDATA[rabbitmq]]></category>
            <category><![CDATA[net-core]]></category>
            <category><![CDATA[polly]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Kevin Patrick Boylan | .NET Software Engineer]]></dc:creator>
            <pubDate>Thu, 22 May 2025 15:13:43 GMT</pubDate>
            <atom:updated>2025-05-22T15:13:43.127Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building Resilient Microservices with .NET Core, Polly, and RabbitMQ</h3><h3>Introduction</h3><p>As someone with experience in developing software in the lifescience manufacturing domain, I’m interested in finding alternatives to more traditional and monolithic approaches. In this domain, system reliability and traceability <strong>aren’t optional </strong>— they’re absolutely critical and essential.</p><p>But I’ve seen from experience just a few of the limitations of the <strong>monolithic approach</strong>: tight coupling, poor fault isolation, difficult deployments, maintenance and troubleshooting are just a few of the shortcomings.</p><p>That’s when I decided to shift toward a <strong>microservice architecture</strong> using <strong>.NET Core</strong>. This new perspective allowed me to envision breaking down large, tightly coupled applications into smaller, focused, and independently deployable services. Each service could then evolve on its own, making the overall system more scalable and maintainable.</p><p>In what follows, I’ll share some of the key lessons, patterns, and techniques I learned while building a simple but resilient microservice-based system with .NET Core, <strong>Polly</strong>, and <strong>RabbitMQ </strong>— with practical insights from real-world implementations.</p><h4>What is Microservice Architecture?</h4><p><strong>Microservice architecture</strong> is a design approach where a system is decomposed into a collection of small, independent services. Each service is responsible for a single business capability and can be developed, deployed, and scaled independently of the others.</p><p>Unlike monolithic applications — where all functionality lives in one large codebase — microservices promote <strong>separation of concerns</strong>. This allows teams to iterate faster, deploy services without affecting the whole system, and choose the most appropriate technologies for each part.</p><p>Some of the key characterstics of a microservice architecture:</p><p><strong>Autonomous and Decentralized</strong>: Each microservice is self-contained, with its own data and logic. It can be developed, deployed, and scaled independently.</p><p><strong>Resilience and Fault Tolerance</strong>: Failure in one service doesn’t bring down the whole system — especially when fault-handling strategies (like those provided by Polly) are in place.</p><p><strong>Loose Coupling and Scalability</strong>: Microservices interact through well-defined APIs or asynchronous messaging systems, reducing dependencies. Individual microservices can be scaled horizontally based on demand (e.g., scaling only the payment service during peak sales time periods).</p><h4>When to Use Microservices</h4><p><em>The system is large and complex enough to benefit from modularization</em><br><em>Multiple teams are working on different parts of the application</em><br><em>Independent scaling and deployment are required</em><br><em>High availability and fault tolerance are business-critical</em></p><p>Bear in mind though, that a microservice architecture can introduce complexity in operations, monitoring, testing, and communication between services. It’s not always the right choice for small or simple applications.</p><p>In my case, the shift to microservices was driven by a need for <strong>scalability</strong>, <strong>resilience</strong>, and <strong>better maintainability</strong> in a production environment that must comply with strict quality and reliability standards.</p><h4>Technology Stack Overview</h4><p>Here’s a quick summary of the technologies I used in my examples.</p><p><strong>.NET Core</strong></p><p>.NET Core was my natural choice, for many obvious and well-known reasons:</p><p>It offers performance and reliability.<br>It has built-in support for modern architecture patterns such as <strong>Dependency Injection</strong> (DI).<br>It has a wide availability (e.g. through NuGet packages) of reliable, open source libraries to extend .NET Core capabilities.</p><p><strong>Polly</strong></p><p>Polly is a .NET resilience and transient-fault-handling library that allows you to configure policies such as Retry, Circuit Breaker, Timeout, and Fallback in a fluent and thread-safe manner.</p><p>Some of my use-case requirements were:</p><p><strong>Retry logic</strong> for an unstable or unavailable message queue.<br><strong>Circuit breaker logic</strong> to prevent cascading failures.<br><strong>Timeout policies</strong> to avoid hanging requests.<br><strong>Fallback strategies</strong> to persist messages (for re-publishing) during partial failure cases.</p><p>Polly turned out to be an extremely straightforward and powerful tool for implementing a resilient and self-healing system.</p><p><strong>RabbitMQ</strong></p><p>Microservices need to communicate, and while REST APIs work well for synchronous requests, they don’t scale well for event-driven or loosely coupled communication. That’s where <strong>RabbitMQ </strong>came in.</p><p>These are just a few reasons I used RabbitMQ:</p><p>It supports asynchronous, decoupled communication.<br>Message queues help absorb traffic spikes.<br>It ensures delivery even when consumers are temporarily offline.<br>With the .NET Core <strong>RabbitMQ.Client</strong> library, message queueing can be achieved quickly with minimal code.</p><h3>First Scenario: When Everything Works</h3><p>In what follows, I want to go through a simple but realistic use case that includes these modules:</p><ol><li>A front-end UI developed with <strong>Angular</strong>. The UI is a simple example of a fictional <strong>Manufacturing Execution System</strong> (MES) application, where users can view and operate different aspects of a pharmaceutical manufacturing process. The back-end database for the MES is <strong>SQL Server</strong>. In my use case, we’ll look at the case of a user adding a new Material (e.g. Cellulose, Lactose).</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LUZ77-p03_KWJc7QO67_Zg.jpeg" /></figure><p>2. A .NET Core API that hosts a <strong>RabbitMQ </strong>publisher service. This service processes requests received from the UI, by publishing them to a RabbitMQ message queue. The payload structure (submitted from the UI) can be viewed in Swagger:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uGDtKXP3G-2ey23AeZY1UA.jpeg" /></figure><p>3. A .NET Core <strong>Worker Service</strong>. This service runs in the background and has just one responsibility: To monitor a RabbitMQ message queue for new messages. When it finds a new message, the message is taken off the queue and inserted into a SQL Server database. The service functions as a <strong>subscriber</strong>, and it has only one job to perform: Transform published Material messages into SQL Server data:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/775/1*ib12JRmlxFH1gO1m_NpEMA.jpeg" /></figure><p>4. A RabbitMQ <strong>message queue</strong> that exists on my localhost. The queue I’ll be using in my examples is AddMaterialQueue, and it is currently empty:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3pjg_WC1jdrHUKUWEhYUig.jpeg" /></figure><p>To publish a new Material message to the queue, I’ll use Swagger to execute a <strong>Http POST</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TInl7hZoBs5mLx3vKPuPZQ.jpeg" /></figure><p>We can now see a new message in the queue:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nI7KvChT6Dq6HFUNoifDfg.jpeg" /></figure><p>And we can view the message payload:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CMKDmb9s2mYxaXbVRfACHw.jpeg" /></figure><p>If I run my subscriber worker service, <strong>MaterialQueueWorkerSvc</strong>, the message is removed from the queue, its payload processed and inserted into SQL Server:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CyMwf7TBiE9j3teq-4_TPg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/643/1*MaPdiBIDtfQu5YN49b3UIQ.jpeg" /></figure><p><strong><em>So far, so good</em></strong>. This was all a very high-level description of a use case executing correctly. But what if something goes wrong?</p><h3>Second Scenario: When Something Goes Wrong</h3><p>There are a number of reasons why a message can fail to publish (i.e. make it successfully onto the queue). In my simple case, my message queue is on the same machine as my APIs and backround services. But in a real-world scenario, a message queue will likely be accessible over a network, which means there can be multiple reasons for publishing failures: Network latency, or delays, server reboots, DNS issues, etc.</p><p>So let’s go through the following use case: one of our front-end users tries to add a new Material, but for some reason the request fails to make it to the message queue. In this case, we assume a Server 500 error is returned to the user.</p><p>Depending on the nature and severity of the problem, the user may (or may not) successfully publish the material message after a second attempt. But if she does not succeed the second time, she might just give up for the day and work on something else. In the meantime, <strong><em>there is no persisted record of the material message</em></strong>. The message is gone, without a trace, and our user will have to try adding it again at some later time.</p><p><strong>Adding Resilience with Polly</strong></p><p>In a distributed system, <strong>bad things can and will happen</strong>. Networks fail, services go down, and queues become temporarily unreachable. The question isn’t whether something will break — it’s <strong>how your system responds when it does</strong>. That’s where <strong>Polly </strong>becomes an essential tool in a .NET microservice architecture.</p><p><strong>Handling Transient Failures Gracefully</strong></p><p>Let’s revisit the scenario from the end of the last section: a front-end user submits a request to create a new Material. But in our current scenario, the API attempts to publish the message to RabbitMQ, but for some reason — a brief network hiccup, DNS timeout, or a short-lived queue server restart — the message doesn’t make it onto the queue. The result? A 500 Internal Server Error is returned, and the user is frustrated by the system.</p><p>Without resilience, this is a dead end.</p><p>With Polly, we can introduce fault-handling logic that automatically retries the operation, or falls back to an alternate strategy (such as logging the failure for later replay), improving both user experience and data integrity.</p><p><strong>Polly in Action: Retry Policy</strong></p><p>Here’s an example of how I used Polly to wrap a message-publishing operation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/765/1*A1kAqoMZz1Xcq0eiMgAFmw.jpeg" /></figure><p>In this example:</p><p>The policy handles transient exceptions like <strong>BrokerUnreachableException </strong>or <strong>TimeoutException</strong>.<br>Retries happen with exponential backoff (2, 4, 8 seconds).<br>A log entry is created for every retry, giving us insight into persistent issues.</p><p><strong>Circuit Breakers for System Protection</strong></p><p>Retries are useful — but in some cases, they <strong>can make things worse</strong>. If RabbitMQ is completely down, for example, retrying repeatedly will only overload the service and slow down the user experience.</p><p>That’s where <strong>circuit breakers</strong> come in:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/926/1*ByS7piqvCrZpHaq5smn9Sw.jpeg" /></figure><p>This prevents the system from making repeated failing calls and gives the failing component time to recover.</p><p><strong>Fallbacks and Graceful Degradation</strong></p><p>Sometimes it’s better to return a meaningful fallback response than a generic 500 error. Polly allows you to define a fallback like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*Ln9Y8zqlPcnEf6jUkC39Xw.jpeg" /></figure><p>Fallbacks don’t fix the root cause, but they allow the system to <strong>degrade gracefully</strong>, buying you time to fix the problem without disrupting user trust.</p><p><strong>Results of Using Polly</strong></p><p>By combining *Retry*, *Circuit Breaker*, and *Fallback* policies:</p><ol><li>Message delivery became far more reliable in the face of transient faults.</li><li>User-facing errors were reduced, even during infrastructure issues.</li><li>Logging and observability improved, helping me diagnose and fix issues faster.</li></ol><p><strong>Ensuring Message Delivery with a Pending Queue Table</strong></p><p>While Polly’s retries and fallbacks can handle <strong>temporary failures,</strong> there are still cases where all retries fail and message publishing isn’t possible in the moment. In these situations, rather than losing the message, we fall back to <strong>persisting it locally</strong> in a dedicated SQL Server table — PendingQueueMessages — for later reprocessing.</p><p>This approach turns a transient failure into a <strong>recoverable one</strong>, using a pattern sometimes called a “<strong>Persistent Outbox</strong>”.</p><p><strong>Fallback to Local Persistence</strong></p><p>Here’s how the fallback works in practice. If all retries to publish to RabbitMQ fail, we write the message payload into the <strong>PendingQueueMessages </strong>table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*KDGKhfQRkdk5Pk_oGlsFgA.jpeg" /></figure><p>This ensures:<br> 1. The original message isn’t lost.<br> 2. We retain full traceability of failed events.<br> 3. Recovery is possible without user intervention.</p><p><strong>An Example of Exception-Handling and Fallback Execution</strong></p><p>Now I’ll go through an example of exception-handling to provide some useful details about three Polly policies: <strong>Retry</strong>, <strong>Circuitbreaker </strong>and <strong>Fallback</strong>. To raise an exception, I simply created a boolean variable <strong>_simulateFailure </strong>with a value of <strong>True </strong>to test my Polly policies. Below is the service method that publishes (when there is no exception, of course) a message to RabbitMQ:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*rhqo1vv3n63D8-iFar2xGA.jpeg" /></figure><p>With _simulateFailure set to True, the method will not successfully publish the message. Because I set RetryCount to 3 in the Retry policy, the method will execute three times before the Fallback policy is executed. The Fallback policy helps ensure that the Json payload from the Http Request is saved in SQL Server. To save, I created a new Repository method to handle the insertion:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*Bna-75_fCcxP8PP49K7Pxw.jpeg" /></figure><p>Then I updated the service method to handle the Fallback scenario. The important thing to notice here is the assignment of the <strong>CreatePendingMessageAsync </strong>repository method to the Fallback policy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/1*JefAKzG6sq2MKHuTS9me7w.jpeg" /></figure><p>Now I’ll create and post a Material request with <strong>Swagger </strong>and we’ll see what happens when _simulateFailure is True.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3_dVkmdiXmZY-Q21SBzaOw.jpeg" /></figure><p>One interesting thing to note in this example is that, although I’m raising an exception three times, the returned response code is 200, indicating success. This makes sense, because our Fallback policy ensures a smooth handling of a scenario where a message cannot successfully publish to RabbitMQ.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uOCTMCSqGgq9IOjFo3URVA.jpeg" /></figure><p>Below we can see that, although the message failed to publish, it was successfully saved to the database. Three important things to note here are the saved Payload Json, the name of the RabbitMQ queue, and the IsPublished flag. With these data points, I can create a background service that monitors the table for unpublished messages and then re-publishes them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bYyw0k7ykCSCrkTUQfaCiw.jpeg" /></figure><p><strong>Background Service for Reprocessing Messages</strong></p><p>To complete the pattern, I created a hosted <strong>.NET Core Worker</strong> background service that periodically scans the <strong>PendingQueueMessages </strong>table and tries to republish any messages that failed previously.</p><p>Here is my simple Worker class. Every 10 seconds, it make an asynchronous call to <strong>ProcessPendingMessagesAsync</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*1DtdJbYT3-H86Pguu3_qWA.jpeg" /></figure><p>The responsibility of <strong>ProcessPendingMessagesAsync </strong>is to query the database for unpublished messages. Retrieved messages are re-published to RabbitMQ and the corresponding database records are updated to IsPublished = 1 (true).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/1*rbkWTywcYvMgi0QzdIBoeg.jpeg" /></figure><p>Just to refresh, let’s recall that we have an unpublished message queued up in our database:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bYyw0k7ykCSCrkTUQfaCiw.jpeg" /></figure><p>I’ll now start the <strong>PendingMessageWorkerSvc </strong>background service. If all goes well, the service will process the unpublished message by successfully re-publishing it and then updating the database record.</p><p>We can see signs of success in the console window output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YWZ90lJHzmrPz3zBlYsCNA.jpeg" /></figure><p>Now we’ll look at RabbitMQ and confirm that the message was successfully re-published:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vInOBLIjA7Rug_biMk5gVA.jpeg" /></figure><p>And finally, we can see that the message was successfully updated in the database:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dZGx3Pn3u_MHpOCmrwov0A.jpeg" /></figure><h3>Conclusion</h3><p>Building resilient microservices isn’t just about choice of architecture (e.g. <strong>Microservice versus Monolithic</strong>) — it’s about planning and designing for failure and recovery from the start. By combining .NET Core, Polly, and RabbitMQ, I created a simple but realistic system that not only scales well, but also recovers gracefully when things go wrong.</p><p>With the implementation of layers of retries, circuit breakers, fallback queues and background reprocessing, each one can add stability to the flow of messages between services. These patterns don’t just improve reliability — they can also give end-users a better experience and give developers peace of mind in a demanding, high-traffic production environment.</p><h3>Further Reading</h3><p>If you’d like to go deeper into the tools and patterns covered in this article, here are some valuable resources:</p><ul><li><strong>Polly Documentation</strong><br> <a href="https://www.thepollyproject.org/">https://www.thepollyproject.org</a><br> Official site with guides on retry, circuit breaker, and other policies.</li><li><strong>Microsoft Docs — .NET Resilience with Polly</strong><br> <a href="https://learn.microsoft.com/en-us/dotnet/architecture/microservices/implement-resilient-applications/implement-http-call-retries-exponential-backoff-polly">https://learn.microsoft.com/en-us/dotnet/architecture/microservices/implement-resilient-applications/implement-http-call-retries-exponential-backoff-polly</a><br> Great overview of applying retries to Http calls in .NET apps using Polly.</li><li><strong>RabbitMQ Tutorials (Official)</strong><br> <a href="https://www.rabbitmq.com/getstarted.html">https://www.rabbitmq.com/getstarted.html</a><br> Hands-on messaging tutorials in multiple languages, including C#.</li><li><strong>MassTransit (for advanced RabbitMQ usage in .NET)</strong><br> <a href="https://masstransit.io/">https://masstransit.io</a><br> If you want to go beyond basic RabbitMQ integration, this framework simplifies pub/sub and sagas in microservices.</li><li><strong>Microsoft Docs — Background Services in .NET</strong><br> <a href="https://learn.microsoft.com/en-us/dotnet/core/extensions/workers">https://learn.microsoft.com/en-us/dotnet/core/extensions/workers</a><br> Useful introduction to creating worker services.</li><li><strong>Martin Fowler on the Circuit Breaker Pattern</strong><br> <a href="https://martinfowler.com/bliki/CircuitBreaker.html">https://martinfowler.com/bliki/CircuitBreaker.html</a><br> A clear explanation of why and when to use circuit breakers in distributed systems.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f11fb83d31e0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Persistence Ignorance with .NET Core API and Entity Framework Core]]></title>
            <link>https://medium.com/@kevinpatrickboylan/persistence-ignorance-with-net-core-api-and-entity-framework-core-96116fb2e31b?source=rss-cdb3e200aa99------2</link>
            <guid isPermaLink="false">https://medium.com/p/96116fb2e31b</guid>
            <dc:creator><![CDATA[Kevin Patrick Boylan | .NET Software Engineer]]></dc:creator>
            <pubDate>Mon, 05 May 2025 15:09:28 GMT</pubDate>
            <atom:updated>2025-05-05T15:11:31.803Z</atom:updated>
            <content:encoded><![CDATA[<h3>Persistence Ignorance with .NET Core API and Entity Framework Core</h3><p><strong>Persistence Ignorance</strong> (PI) is one of those design principles you may have been following in your <strong>API development</strong> even if you hadn’t heard the phrase before. For a long time, I have appreciated and developed API applications with a strict separation between service layers (i.e. business logic) and data persistence layers (i.e. data access). But I only recently heard of the concept of PI, in spite of the fact that I have tried whenever possible to code my APIs in accordance with it.</p><h4>What Is Persistence Ignorance?</h4><p>Put simply, an API that adheres to PI keeps its service layer decoupled from the persistence layer. Imagine a typical API <strong>HttpGet </strong>controller pattern, as shown here:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QY19Q_tadk2EruIpmr_Xaw.png" /></figure><p>In this example, I have two services that are injected into the controller constructor, but for now I’ll focus on the GetRoomHumidityList method. The responsibility of this method is to return a set of room humidity data to a front-end UI that displays the data in a browser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MeCXvWwfp9JJEltPeugdoQ.png" /></figure><p>The projects for this example are based on simple use cases taken from a pharmaceutical manufacturing context. In a <strong>SQL Server</strong> database, I have humidity and timestamp data stored, the purpose of which is to give my fictional factory floor operators real-time visiblity into fluctuations (i.e. exceptions) in factory room humidity readings.</p><p>One way to demonstrate the benefits of PI is to go through and compare two simple examples: one that does not adhere to PI, or in another words, one that demonstrates <strong>Persistence Awareness</strong> (PA). PA refers to a service layer that contains data persistence objects and actions.</p><p>My second example will demonstrate PI. I’ll compare the two examples, and hopefully show that the second example is preferable to the first.</p><h4>An example of Persistence Awareness</h4><p>In this example, we’ll see the coupling of service (business logic) concerns with data access concerns. Here, again, is the controller method:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/859/1*MVZ8GJ_OkW7k2px-tMtU9A.png" /></figure><p>This method receives a simple <strong>DTO </strong>object that is required for querying the database with RoomId and BatchId parameters. The object is passed to the Execute method of GetRoomHumidityUseCase:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*nR70WSSIwinxc9w0ietAAg.png" /></figure><p>After data is retrieved, a service class processes and analyzes the data, using <strong>ML.NET</strong>. A DTO Response is created and returned to the front-end UI. I won’t go into <strong>machine learning</strong> here since it is way outside the topic of PI, but here is a partial screenshot of the service method that processes the dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*LFgZ2_r9mcAdIkkO2u1f1w.png" /></figure><p>Let’s now have a look at what makes this a case of PA. Here is the entire <strong>GetRoomHumidityUseCase </strong>class, with some highlighting in red:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*XmLXKvJfOOqeVwG7XX0Ofg.png" /></figure><p>At the very top, there is a <strong><em>using Microsoft.EntityFrameworkCore</em></strong> declaration. That’s our first clue that indicates a mingling of service and data concerns. Further down, we see additional signs of coupling:</p><p>1. Injection of an <strong>EF DbContext</strong> object into the constructor.<br>2. In the Execute method, the context object is used to query the HumidityReadings table.</p><p>All of this is a very short but clear example of Persistence Awareness. PI is my preferred way to separate service and data concerns, as we’ll see.</p><h4>An example of Persistence Ignorance</h4><p>In this second example, here is a refactored version of the GetRoomHumidityUseCase class:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/843/1*qaTbkRF5O8G9_DvOrSleUA.png" /></figure><p>Compare this to the first example, and you’ll immediately notice the complete absence of any references to <strong>Entity Framework Core</strong> (EF Core). This is exactly what we want, and it was accomplished by using an instance of _roomRepository instead of DbContext (which is obviously a pretty tight coupling to EF).</p><h4>Repository Pattern</h4><p>Let’s quickly review the <strong>Repository Pattern</strong> (RP) I implemented to decouple my Humidity service from the persistence layer (EF Core, SQL Server). First, here is the interface:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/657/1*W6mVoZVPWPoAPyXT7VvRtw.png" /></figure><p>And here is one implementation of IRoomRepository:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/679/1*9SDn8Yg8lXP5fETrz3DQMw.png" /></figure><p>As you can see, my EF operations take place here, outside my service. I prefer this approach, but maybe you’re not yet convinced. Maybe it looks like unnecessary refactoring, and perhaps you might even prefer the first example because there is obviously less code used to accomplish what the second example does.</p><p>So let’s go through another example which will hopefully demonstrate the benefits of PI.</p><h4>Database Ignorance and Dependency Injection</h4><p>In this example, I want to go through a use case where we need to, with as little re-engineering as possible, make a second database provider available to our API. In this case, I have exported my <strong>SQL Server</strong> database to <strong>PostgresSQL</strong>.</p><p>My requirement was to be able to retrieve room humidity data from either SQL Server or PostgresSQL, based on a simple setting stored in my API’s <strong>appSettings.json</strong>. I also needed another setting that gives the correct connection string for each database provider.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*cejQkM3C3_sgxX0QdE1BWA.png" /></figure><p>The next task was to create a new repository class for PostgresSQL access. Red highlights in the screenshot indicate this repository uses the .NET PostgresSQL library:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*wfOBo0zxIOZRek2IMaU1oQ.png" /></figure><p>The final task was to add a combination of <strong>dependency injection</strong> (DI) and conditional logic in Program.cs to get the correct database provider.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*HCnfUczuwRyY4tM042r3EQ.png" /></figure><p>Based on the DbProvider setting, dependency is injected for either PostgresRoomRepository or SqlServerRoomRepository. Then the DbContext is initialized, using either the PostgreSQL or SQL Server connection string.</p><h4>Conclusion</h4><p>The last thing I did, of course, was a full test run, testing with my front-end UI. By simply changing one setting in the API, I could easily point my API controller methods to either SQL Server or PostgresSQL. This is a simple but I think compelling example of the benefits provided to an API architecture by applying Persistence Ignorance.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=96116fb2e31b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using JWT Authentication and BCrypt.Net with Angular and .NET Core Web API]]></title>
            <link>https://medium.com/@kevinpatrickboylan/using-jwt-authentication-and-bcrypt-net-with-angular-and-net-core-web-api-51aab1153778?source=rss-cdb3e200aa99------2</link>
            <guid isPermaLink="false">https://medium.com/p/51aab1153778</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[hashing]]></category>
            <category><![CDATA[net-core]]></category>
            <category><![CDATA[jwt-token]]></category>
            <dc:creator><![CDATA[Kevin Patrick Boylan | .NET Software Engineer]]></dc:creator>
            <pubDate>Tue, 25 Mar 2025 17:43:20 GMT</pubDate>
            <atom:updated>2025-03-25T17:45:25.045Z</atom:updated>
            <content:encoded><![CDATA[<h3>Using JWT Authentication and BCrypt.Net with Angular and .NET Core Web API</h3><p>While working recently on a personal project, I added a new login form to my <strong>Angular </strong>site. While the username/password authentication was straightforward enough (more on this later), I also needed a quick implementation of web session management capable of raising events such as redirects of users to a login page if the user has been inactive for a certain amount of time. Think of a use case where a user leaves her desk for an hour. When she returns, she should be redirected to login with her credentials.</p><p>As part of this change, I also updated my user management system. This is an area in my site where I can view, add and edit users. The site is a simple example of an ERP portal UI that manages objects for a fictional pharmaceutical manufacturing company <strong>ApexPharm</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qvtFXyLaoYn_Zql0wALAHw.png" /></figure><p>When I first created the user system, my API Controller method for inserting the user into a <strong>SQL Server </strong>database was inserting the password as plain text. A very bad idea, of course, but this is my localhost application and I wanted to get the <strong>CRUD </strong>operations for managing users working as quickly as possible. But I recently revisited the API and decided to replace the plain text insert with something more secure.</p><h4><strong>BCrypt.Net</strong></h4><p><strong>BCrypt.Net</strong> is an easy to use, open source .NET library for hashing and verifying passwords. To use it, simply browse for it in Visual Studio’s <strong>Nuget Package Manager</strong> and install the latest stable release.</p><p>Since this is not the place for a lengthy side-by-side comparison of hashing and encrypting, I’ll just mention that, for password storage and verification, hashing is generally a better choice than encryption. One important reason for this is that hashing is a <strong>one-way process</strong>. That is, you cannot reverse it to retrieve the original password. Imagine an attacker who gains complete access to your <strong>database</strong>: he’ll have access to the hashed passwords but will not be able to retrieve the originals.</p><p>Encryption, on the other hand, is a <strong>two-way process</strong>. With access to an encryption key, attackers can retrieve the original password.</p><h4>Using BCrypt.Net with .NET Core Web API</h4><p>In my front-end UI, I have a form for adding a new user:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5IsaCPtwGkH9cB6KMKJkKA.png" /></figure><p>When the Submit button is clicked, the form data is posted to a <strong>Web API</strong> controller method. In this method, a service that processes the userEntity is called:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*ryk44IXeEnbCvikTzeZy1g.png" /></figure><p>The service method calls a static helper class PassWordHelper to hash the posted password. The hashed password is returned and assigned to the Password property of the user entity:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/695/1*hjr4aLlj9fqxjKLkk7pFXQ.png" /></figure><p>And last, here is the code that calls the BCrypt.Net library:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*UfuXbbeI1uSk6DnuoPSOcw.png" /></figure><p>So now I’ll add a new user and then look at the database. First, I’ll submit the form:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y-fZOqtYD-0Ve3L4OtyIkA.png" /></figure><p>After a successful insert, I am redirected to the users list page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0y8To5iV55YHShkjQTEe-A.png" /></figure><p>I’ll open the Users table in the database to see what the password looks like for the new user:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uF5pJQg7R53z5K8EqqjUBw.png" /></figure><p>This fulfills my security requirement: a hashed password generated by a <strong>one-way</strong> process that can’t be reversed to the original password. So let’s now go to my second requirement, the proper managing of user login sessions with <strong>JWT Authentication</strong>.</p><h4>JWT Authentication and the Back-End API</h4><p><strong>JWT </strong>stands for <strong>JSON Web Token</strong>. It’s a self-contained token that wraps, in <strong>JSON </strong>format, information typically generated from an API resource. There are several different token types (such as refresh tokens and access tokens) but my example focuses on <strong>ID tokens</strong>.</p><p>My requirements for this simple example are:</p><ol><li>After successfully authenticating user credentials, the Web API AuthController has to generate and return an ID token to the calling application (the Angular UI).</li></ol><p>2. The UI has to store the returned token locally, that is, in the user’s browser.</p><p>3. The UI has to read the value of the token’s time-out period. In my case, I would like it to be 30 minutes.</p><p>I want all pages, including the home page, to require a valid token. Unless the user has a valid token stored, none of the pages (except for the login page) should be accessible.</p><h4>The AuthController and Token Generation</h4><p>Before generating an ID token, my controller first validates the posted username and password. The database is queried with the username and hashed password. My PasswordHelper class verifies that the submitted password matches the hashed password in the database.</p><p>First, the AuthController Login method, where I call a service method to validate the credentials:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/861/1*cFJvbDQaKsm3-wk6zgrCyQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/1*mlnxWmrLc_gDDRZKuM0b0g.png" /></figure><p>PasswordHelper.Verify is a static class method that uses BCrypt.Net to compare the submitted password to the hashed version in the database:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*0O23n9A6YqOTQJejwv9AoA.png" /></figure><p>If the validation fails, the login fails and no token is generated. If validation succeeds, then a JWT ID token is generated and returned.</p><p>Let’s look again at the Login controller method, where the service method for creating a token executes after successful validation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/835/1*tm9Eqmcib7xXT_kzmjrylA.png" /></figure><p>The code responsible for building the JWT token resides in my <strong>GenerateTokenUseCase </strong>service class. It has only one purpose, which is to take the posted User entity as a parameter and build a token.</p><p>In this example, there are three namespaces that are required for JWT generation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/523/1*ITWY17o2ktyjEG3ituoAhg.png" /></figure><p>Two important things to note here are the secret key and expiry duration properties. The secret key is a required parameter of the <strong>SymmetricSecurityKey </strong>class constructor. This constructor initialises a key, which is then passed as a parameter to initialise a <strong>SigningCredentials </strong>object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*zfJ0GYcSOcs_RJ-JXFjEvQ.png" /></figure><p>I want users to have token expiry duration of 30 minutes, so I set this value in <strong>appSettings.json</strong>, retrieve the value and use it to initialise a new token object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*KKPkC97Kj5gMEtOeb80LLA.png" /></figure><p>The appSettings.json has a section I added for storing JWT settings:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/446/1*9mqk3Ii824w5Gvmc3hei5g.png" /></figure><h4>JWT Authentication and the Front-End UI</h4><p>Ok, so after completing the back-end updates and testing with <strong>Swagger</strong>, I can now test the Angular front-end changes. Here is the login form:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kwNed-X30ZjNLvgaL0_rew.png" /></figure><p>A quicky summary of the Angular components required for user login:</p><ol><li>The Login HTML component.</li><li>The Login component for input and business logic validation.</li><li>The Login service component for posting the login request to the API.</li><li>The Login model component for representing a Login entity.</li></ol><p>The Login service is short and simple, calling just one controller method at the Auth endpoint:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/530/1*2wsm8NKXY3_mKiL6OmsABw.png" /></figure><p>As I mentioned earlier, if the posted credentials are authenticated, the Auth controller returns an ID token to the UI for storage. While debugging, I <strong>console.log</strong> from my Login component to verify a successful return of token:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/593/1*FC_dY-cClEJf_EMkq22z-Q.png" /></figure><p>If I open the browser console and login with the credentials of our newest user <strong>James Joyce</strong>, I can confirm that a token has been successfully returned:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*navQ0t-L9uqHR6GJ17zr5w.png" /></figure><p>After a successful login, the “Login” link text in the navigation menu changes to “Logout”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cd5JMVpneJ7qxLOpSmppHg.png" /></figure><p>By clicking Logout, the stored token is removed from local storage and the user is redirected to the Login page (“Logout” then changes to “Login”).</p><p>Both user actions such as clicking Logout and application events such as token expiration are handled in a separate service component in Angular:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/522/1*hjppnqdh6_-Z5xGV3NhxFQ.png" /></figure><h4>Conclusion</h4><p>So without much effort and time, I was able to implement changes to meet my requirements for secure password storage and management of web UI sessions with JWT tokens. This was a very short and quick tour of these concepts but I hope there’s enough here to get you going if you are new to these ideas.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=51aab1153778" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using RabbitMQ with .NET Core Web API and Worker Services]]></title>
            <link>https://blog.devops.dev/using-rabbitmq-with-net-core-web-api-and-worker-services-15330c53cfb0?source=rss-cdb3e200aa99------2</link>
            <guid isPermaLink="false">https://medium.com/p/15330c53cfb0</guid>
            <category><![CDATA[rabbitmq]]></category>
            <category><![CDATA[net-core]]></category>
            <category><![CDATA[message-queue]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Kevin Patrick Boylan | .NET Software Engineer]]></dc:creator>
            <pubDate>Wed, 19 Feb 2025 18:30:22 GMT</pubDate>
            <atom:updated>2025-03-03T18:08:55.400Z</atom:updated>
            <content:encoded><![CDATA[<h3>Using RabbitMQ with .NET Core Web API and Worker Services</h3><p>I won’t dive into the <em>Microservice vs. Monolithic</em> question because it’s a big and complex one and way beyond the scope of what I’m sharing here. Put simply, each architecture has its pros and cons depending on an organization’s requirements, skillsets, etc.</p><p>But I thought it might be fun to create and compare simple examples of the two approaches. In what follows, I’ll first go through the more traditional “monolithic” approach to adding new items to a database. Then I’ll go through a very minimal version of the microservice approach. Both approaches have the same result: inserting a new item to a database from a web UI.</p><h4>The Front-End</h4><p>I have a simple <strong>Angular </strong>site that models an equally simple and fictional pharmaceutical manufacturer’s <strong>ERP </strong>UI. It has the typical <strong>CRUD </strong>operations you would expect in this type of application. In what follows I’ll the use the example of Materials, a core entity in the world of biopharma manufacturing. Here we can view materials, add new materials, edit existing materials, and mark materials as Inactive (we don’t delete in any of my use cases).</p><p>Here is the grid that displays a list of materials:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BTu50R8elucR39fQfqCq_A.png" /></figure><p>Let’s imagine that we need to add a new material. This company is producing a new product which requires materials that don’t yet exist in their ERP database. The database is <strong>SQL Server</strong>. Here’s a view of material data with SQL Management Studio.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lozlsmYllKGU-h39mqHuVA.png" /></figure><p>Let’s go to the Add New Material form and add our new material Povidone which will be used to manufacture a new medicine.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oX4rUgzScMzOQZbUrFcb5A.png" /></figure><p>The material was successfully inserted into the database:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*MtewRUCRxgchYFka4W8lyg.png" /></figure><h4>The Back-End</h4><p>In this case, the insertion of the material was handled by a pretty typical .NET Core API controller pattern. An Angular service component posts a serialized Material object to a remote controller method:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*UWWkNowmN4uvMxDKhdBkXQ.png" /></figure><p>The controller makes a call to a service level instance of CreateMaterialUseCase. Its Execute method passes the material object to a repository method:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/871/1*leOsMcedYGdWqt7v94OJmA.png" /></figure><p>The repository method CreateMaterialAsync inserts the material using <strong>Entity Framework</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*T3TLPkMnCYZlh0LH5EkqBA.png" /></figure><p>So far, this is all very simple boilerplate controller architecture. In our case of adding a new material, what real world problems could occur that would prevent successful inserts to the database? If the database is offline for some reason, the insert will obviously fail. In this case, it’s likely a 500 internal server error will get returned to the UI.</p><p>We can also ask if this is the ideal pattern to follow in terms of scalability, e.g. think of a site that directly inserts to a database several thousand times in a hour.</p><p>Considering the scenario of an offline database is a good segue into looking at how message broker frameworks such as RabbitMQ offer an alternative to the more monolithic pattern we just looked at.</p><h4>Message Brokers</h4><p>Let’s first briefly describe how a message broker framework works. At the heart of it is the message queue. The queue is an in-memory buffer for storing messages. Being a queue, it is a FIFO (first in, first out) data structure. If you’re a developer who has been working with Windows and the Microsoft development stack for a long time, you might already be familiar with <strong>Microsoft Message Queue</strong> (MMQ).</p><p>Producers of messages typically publish them as serialized (Json) instances of entity or class objects. These messages are placed in a queue where they will just sit indefinitely if there is no consumer.</p><p>The consumer is an application or service that receives and processes messages from the queue. Typically, but not always, the consumer is a constantly running process, such as a Windows service.</p><p>In our case, the middleware that makes the producer-consumer relationship possible is <strong>RabbitMQ</strong>. It is free, open source and appears to have excellent support and documentation. The website is <a href="https://www.rabbitmq.com/">here</a>.</p><p>Let’s have another look at our API controller application and go through my implementation of the message producer we’ll use to insert new materials.</p><h4>The RabbitMQ Service</h4><p>I wanted to create an alternative to inserting to a database in my API application. So the first thing I did was create a class that uses the RabbitMQ client package for .NET Core (available through NuGet, of course) to receive an incoming class object and then push a serialized version onto a message queue.</p><p>The class is <strong>GenericRabbitMQService&lt;T&gt;</strong>. The reason I want to handle <strong>generic </strong>objects is that in the future I’ll want to push messages from different entities (Material, User, Product, etc.) to <strong>one </strong>method. I don’t want to rewrite what would be mostly duplicate code each time I need to publish a new entity type.</p><p>Here is the class:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*aIJcS_n91WZ1RVHIww8mEg.png" /></figure><p>As you can see, there is just one method, <strong>PublishAsync</strong>, that takes two parameters: a <strong>T item</strong> and an instance of <strong>MessageBus</strong>. MessageBus is a simple model class that stores two items of information required by RabbitMQ: host name (in this case, <strong>localhost</strong>) and queue name (in this case, <strong>CreateMaterial</strong>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/371/1*P_Nmk-GnWwlnK5omj03wEg.png" /></figure><p>There are three sections in <strong>GenericRabbitMQService </strong>that deserve attention. With the <strong>channel.QueueDeclareAsync</strong> call, we are instantiating the message queue. In this case, the queue is named <strong>CreateMaterial</strong>. If the queue exists, our message will be pushed onto it. If not, the queue is created and the message is pushed onto it.</p><p>Second, we use Newtonsoft.Json to serialize our incoming Material object into a Json string. Think of this step as the transformation of a C# object into a publishable, queue-friendly Json object.</p><p>And last, the Json object is pushed onto the queue with <strong>channel.BasicPublishAsync</strong>. Not too bad for what amounts to ten lines of code!</p><p>I call <strong>PublishAsync </strong>from another service level class, <strong>PublishCreateMaterialUseCase</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*yTIjO3PALmuh1gy1ogSLqA.png" /></figure><p>The last thing to do was create a new HttpPost controller method. This method calls the Execute method implemented in PublishCreateMaterialUseCase.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/1*zx87w30NC1cjDq9GI9V9bw.png" /></figure><p><strong>The Front-End Again</strong></p><p>So let’s assume that we’ve successfully tested our new RabbitMQ version of the CreateMaterial controller with <strong>Swagger</strong>, <strong>Postman</strong>, etc. We now need to update our Angular front-end to submit new materials to the RabbitMQ controller.</p><p>I want this update to be configurable. That is, I want to be able to choose between the new and old controllers by changing a configuration setting, not by manually changing the (hard-coded) endpoint URL in my component service code.</p><p>So I added a config.json file that has the settings I need to meet this requirement.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*Et2ziIFZL2IMRyJDle76Fw.png" /></figure><p>If <strong>useMessageQueue</strong> is true, then new materials will post to the RabbitMQ controller. Otherwise, they post to the original controller.</p><p>Here is the updated version of my material service component. You can see the conditional logic that checks the new setting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*0b3nYOGPjZ2hQrTpUIyXJA.png" /></figure><p>Before I add a new material to test the Angular update, let’s have a quick look at the RabbitMQ UI. The UI is a convenient way to view queues and messages on your localhost. My version looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ubFxfwktZCeHvUIyTtbLTQ.png" /></figure><p>At the moment my CreateMaterial queue is empty. Let’s add a new material, Sodium Starch Glycolate, and see what happens:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jYt0vqtfLWbS90BAVuY1iA.png" /></figure><p>If we go back to the RabbitMQ UI, we can now see there is one message in the CreateMaterial queue:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*emAslp7v_7HUm9muZXlS2Q.png" /></figure><p>We can drill down and view the message:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bglEP7TO3lb31sXmKy__Og.png" /></figure><p>Very cool, but now what? We want this message that is now sitting in a queue to become a new material record in our ERP database. How does this happen? We need a service that will <strong>consume </strong>the message so I’ll now describe how the consumer works.</p><h4>The .NET Core Worker Service</h4><p>As I mentioned earlier, a good candidate for message consumers is a running process like a Windows service. In my example, I’ll go through a simple little example of a .NET Core Worker service. We’ll see how it monitors the RabbitMQ queue for new messages and how it processes messages.</p><p>Here’s a view of the directory and file structure in Solution Explorer. I’ll go through some of the classes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/369/1*qoT3nfOSx5nyU1_UFmIQ4Q.png" /></figure><p><strong>Program.cs</strong> is where the service is configured and run. It’s where we add our Worker class as a hosted service to the application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*mT48m3rf7kimkwrY_ZN4Lg.png" /></figure><p><strong>Worker.cs</strong> is where, well, all the work takes place. It is the process that runs and does, at a configured time interval, something. In this case, we want it to watch two RabbitMQ queues, <strong>CreateMaterial</strong> and <strong>UpdateMaterial</strong>, and consume any messages from them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/926/1*aCLJC0UHQLiZ7TRG3h9PPw.png" /></figure><p>In our case, we want the worker to check the queues every 5 seconds. This line configures the time span:</p><p><strong>private readonly TimeSpan _stoppingCheckInterval = TimeSpan.FromSeconds(5);</strong></p><p>RabbitMQ provides event handlers which are raised when a message is found:</p><p><strong>_createConsumer = new EventingBasicConsumer(_channel);<br>_createConsumer.Received += CreateMaterialReceivedHandler;</strong></p><p><strong>CreateMaterialReceivedHandler </strong>is pretty straightforward.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*f44GXq2bvZyIxx1MeHDx1A.png" /></figure><p>When it executes, the message string is deserialized to a Material entity which is then passed to a repository method. This method inserts the Material into the database using <strong>ADO.NET </strong>and a <strong>stored procedure</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/689/1*1PKPOLy1EhZvhjEa8-DwzQ.png" /></figure><p>The last thing we need to do is run the worker service and confirm that it picks up our new material message and inserts it to the database. First, we can see the console output from the service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BMzTHKy8mNAlMv6x6Dp2AQ.png" /></figure><p>If we go to the RabbitMQ UI, we can see that there are no messages in the CreateMaterial queue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zdNlmQdTv77W7q3etTfrsw.png" /></figure><p>And last, we confirm that the material is in the database and appears in the ERP UI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/1*4PndpbHMZDiRgqEIMdYEhA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dEYN0GLJScIJAU17uugfvw.png" /></figure><h4>Summary</h4><p>So we saw two simple examples of taking a material entity posted from a UI form and inserting it to a database. In the first case, the database operation occurs in the same application as the controller.</p><p>In the second case, instead of directly inserting to the database, we serialize the material entity into a Json string and push it onto a message queue using the RabbitMQ client for .NET Core. The message is consumed by a running worker service application, which inserts the deserialized message into the database.</p><p>I won’t conclude this by expressing a preference for one approach or another. I think both approaches have their pros and cons. Depending on your organization’s requirements, <strong>SDLC </strong>approach, team member skillsets and a host of other factors, one of the two approaches will probably strike you as more suitable than the other.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=15330c53cfb0" width="1" height="1" alt=""><hr><p><a href="https://blog.devops.dev/using-rabbitmq-with-net-core-web-api-and-worker-services-15330c53cfb0">Using RabbitMQ with .NET Core Web API and Worker Services</a> was originally published in <a href="https://blog.devops.dev/">DevOps.dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Simple Comparison of XUnit and Angular Testing of API Controllers]]></title>
            <link>https://medium.com/@kevinpatrickboylan/a-simple-comparison-of-xunit-and-angular-testing-of-api-controllers-0cfaf6aa7ca9?source=rss-cdb3e200aa99------2</link>
            <guid isPermaLink="false">https://medium.com/p/0cfaf6aa7ca9</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[api-development]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[net-core]]></category>
            <dc:creator><![CDATA[Kevin Patrick Boylan | .NET Software Engineer]]></dc:creator>
            <pubDate>Thu, 13 Feb 2025 16:24:47 GMT</pubDate>
            <atom:updated>2025-02-13T16:55:29.684Z</atom:updated>
            <content:encoded><![CDATA[<p>I’m a .NET software engineer with over 20 years of experience but I’ve only recently gained some experience with <strong>Angular</strong>. While I have a good bit of experience using <strong>XUnit </strong>to test .NET Core controller methods, I’ve just started looking closely at testing API calls within Angular projects.</p><p>What I’ve learned so far during my deeper dive into Angular is that it was actually helpful for me to do a side by side comparison of XUnit and Angular testing patterns. By trying to map one pattern to the other, I found the Angular pattern much easier to follow and understand.</p><p>Let’s start with a simple example of an API controller method. I’ve tested this method with both XUnit and Angular.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g7cKNNv_10zbq7GVQorFRQ.png" /></figure><p>You’ll notice that a service level method is called in the controller.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/1*IvBGKWVDKslQAlP3G1fuGQ.png" /></figure><p>If you’re familiar with <strong>AutoMapper</strong>, you’ll see that I’m mapping an <strong>entity class</strong> (populated by a database query) to a <strong>DTO </strong>(Data Transfer Object). In this example, the data comes from this table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/719/1*Qws8EkMIlFMj0Gj_qKdFZg.png" /></figure><h3>The XUnit Version</h3><p>So let’s first look at how I tested with XUnit:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*um55dYduoEZt0fYeRAGozA.png" /></figure><p>A very simple example of Arrange/Act/Assert. In the Arrange, I’ve created two MaterialDTO objects and mocked a call to the GetMaterials service method.</p><p>The Act is simply calling the controller, made possible by the mock service call (I won’t discuss <strong>Moq </strong>or <strong>dependency injection</strong> here, since these are big topics best left for another day).</p><p>And last, we have three Asserts to verify that the controller does what it’s supposed to: return a list of Materials. So how does all of this map to Angular testing patterns? In what follows, I’ll give a quick summary of the Angular test I created and a comparison to XUnit.</p><h3>The Angular Version</h3><p>In my Angular project, I have a HTML component that displays a grid of Materials data. As you’ve probably guessed, the data displayed here is returned with a call to the API controller I described above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wVe8_GjisGFTQTy-IBQp0w.png" /></figure><p>This is the Material List HTML component (in the world of MVC, we might call this the view):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*ndESTlhXMLggRpyziwCoAQ.png" /></figure><p>And this is the Material List service. Very simple so there’s not much to explain here: it calls the Material controller and if the API returns materials, they are mapped to a TypeScript array of Material objects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*q5p_TzEgAUDB9yer-xjGiQ.png" /></figure><p>“Between” the HTML component and service, we have the Material List component.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*0lOwlfi_UWKtB0NV2wIshw.png" /></figure><p>This component is responsible for calling the service method and making the returned data available to the HTML component through binding.</p><p>We are successfully populating the HTML grid but now we need to create an Angular test. Here is the test I created:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2xcP2GRh2m-TIhUCrc0eqg.png" /></figure><p>Referring back to our XUnit example, I’ll now locate and describe the Arrange/Act/Assert sections of the test. First we have the Arrange section. Similar to Arrange in XUnit, its purpose is to declare and initialize all the required objects for the test. I put a red border around the Arrange code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/1*aoJJTY-zjLGS6QKOoxWFdw.png" /></figure><p>Before the beforeEach block, we are declaring two instances required for the test. Inside beforeEach, a few things happen.</p><ol><li><strong>HttpClientTestingModule </strong>is imported. It is required because it will mock HTTP requests and responses.</li><li>The <strong>TestBed </strong>object injects the MaterialService into the test.</li><li>TestBed injects <strong>HttpTestingController </strong>into httpMock to mock the HttpGet call to the controller.</li></ol><p>The last bit of initialization is shown here, where two mock material objects are created:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XbZXyHwQc1tYxeW_4LZwcw.png" /></figure><p>It should look familiar if you go back to my earlier example of mocked materials in the XUnit test:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/1*S2mnLj2h8R4zrbz3MEsdnQ.png" /></figure><h3>Comparing XUnit and Angular</h3><p>As for the Act part, in both XUnit and Angular test, we are calling the same controller method.</p><p>In Angular:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/379/1*Q2LZ0FvFVLaW3ahoRwyM1Q.png" /></figure><p>In XUnit:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*CJQQM5qDZiGttLBhMUiOIA.png" /></figure><p>The equivalent of Assert in Angular is pretty straightforward. Just look at the “expect” calls and you should immediately recognize that they have a similar meaning to XUnit’s Assert. I added a few console.log lines to output the Expect results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/834/1*jX5XN4xUHVQeOXLK9rJr0w.png" /></figure><h3>Concluding Thoughts</h3><p>My goal here is to help those like myself who have experience and confidence with XUnit testing of .NET Core controllers but are new to the world of Angular, especially the testing features. I hope you found this useful!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0cfaf6aa7ca9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>