<?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 Mangesh Gaherwar on Medium]]></title>
        <description><![CDATA[Stories by Mangesh Gaherwar on Medium]]></description>
        <link>https://medium.com/@dotnetgik?source=rss-6003542fffd8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*BHkjo405HrZgLu7mEWd-GQ.jpeg</url>
            <title>Stories by Mangesh Gaherwar on Medium</title>
            <link>https://medium.com/@dotnetgik?source=rss-6003542fffd8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 01:29:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dotnetgik/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[Your pod doesn’t need a password. It needs an ID card.]]></title>
            <link>https://medium.com/@dotnetgik/your-pod-doesnt-need-a-password-it-needs-an-id-card-dbba6dd715be?source=rss-6003542fffd8------2</link>
            <guid isPermaLink="false">https://medium.com/p/dbba6dd715be</guid>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[azure-workload]]></category>
            <dc:creator><![CDATA[Mangesh Gaherwar]]></dc:creator>
            <pubDate>Sun, 09 Aug 2026 18:30:56 GMT</pubDate>
            <atom:updated>2026-08-09T18:30:56.451Z</atom:updated>
            <content:encoded><![CDATA[<h3>How AKS, a managed identity, and one very picky bouncer let a pod talk to Service Bus and Key Vault without ever holding a secret</h3><p>Somewhere in your cluster right now, there’s probably a connection string. It’s sitting in a Kubernetes Secret, or worse, an env var, quietly waiting for someone to git commit it by accident or paste it into the wrong Slack channel. It never expires on its own. Nobody remembers who last rotated it. It works exactly the same whether it&#39;s in the hands of your app or a stranger who found it in a public repo.</p><p>There’s a better way, and it doesn’t involve a single password anywhere in the chain.</p><h3>The old way: prove you know a secret</h3><p>Every integration used to boil down to the same pattern: your app holds a piece of knowledge — a connection string, an API key, a client secret — and shows it whenever it wants in. The service on the other end doesn’t actually know <em>who’s</em> asking. It just checks if the secret matches. If it leaks, so does everything downstream of it, and nothing about the system will tell you that happened.</p><h3>The new way: prove who you are</h3><p>Azure Workload Identity flips the model. Instead of your pod <em>knowing</em> something secret, it <em>is</em> something specific — a real, provable identity — and it proves that with a token that expires in minutes and gets reissued automatically. Nothing long-lived ever touches disk.</p><p>Here’s the whole cast of characters:</p><p><strong>AKS cluster</strong> — plays hype man for its own pods, vouching for them by signing tokens on their behalf</p><p><strong>Managed identity</strong> — the “who.” An ID card with nothing on it until everyone else agrees to trust it</p><p><strong>Federated identity credential</strong> — the world’s pickiest bouncer: “I’ll only let in tokens signed by this exact cluster, claiming to be this exact pod. No exceptions, no fake IDs”</p><p><strong>RBAC role assignments</strong> — the guest list at each door: “this identity, and only this identity, may come in and do this one thing”</p><p>None of these four things contain each other. They’re independent objects that reference each other by ID — there’s no structural “wiring,” just fields pointing at other objects’ IDs.</p><h3>The identity isn’t one ID. It’s three.</h3><p>This is the part that trips people up the first time. A managed identity isn’t just one ID — it’s three, like a spy with a different name for every safe house:</p><p><strong>Resource ID</strong> — full path to the identity object. Used for the federated credential’s parent reference.</p><p><strong>Principal ID</strong> — the Azure AD object ID, what RBAC checks. Used by every role assignment, on Service Bus and on Key Vault.</p><p><strong>Client ID</strong> — the Azure AD app ID, used for authentication. Used by the Kubernetes ServiceAccount annotation, and the pod’s runtime env vars.</p><p>Principal ID answers “what is this allowed to do” — authorization. Client ID answers “who is this claiming to be” — authentication. Mix them up in a role assignment and Azure won’t yell at you kindly; it’ll just quietly deny everything and let you debug it for an hour.</p><p><strong>Bonus twist:</strong> when the managed identity is created, Azure secretly creates a second, linked object behind the scenes — a <strong>service principal</strong>, sharing the same principal ID. A bit like ordering a “small coffee” and the barista also handing you a receipt with a different name on it for tax purposes. This service principal is the object RBAC actually checks against. The managed identity is just the friendly, secret-free front end so nobody has to babysit that service principal’s credentials by hand.</p><h3>The trust chain, end to end</h3><p><strong>Setup phase — done once, by a human, hopefully sober</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vWt0_zfbiSoTdwIr24P6og.png" /></figure><ol><li>The AKS cluster publishes its OIDC issuer and runs the workload identity webhook — basically declaring itself the trustworthy office building that vouches for everyone who works there.</li><li>A managed identity is created for the app — an ID card fresh off the printer, blank, unimpressive, allowed to do absolutely nothing yet.</li><li>A federated identity credential links that identity to one exact Kubernetes ServiceAccount — “trust tokens from this cluster’s issuer, claiming to be system:serviceaccount:&lt;namespace&gt;:&lt;service-account-name&gt;.&quot; No plus-ones, no &quot;close enough.&quot;</li><li>Role assignments grant that identity access to specific resources — receive rights on one Service Bus queue, read rights on Key Vault secrets. Scoped narrowly, not “sure, take the whole vault, what could go wrong.”</li><li>The Kubernetes ServiceAccount is created, annotated with the identity’s client ID, and labeled azure.workload.identity/use: &quot;true&quot;.</li><li>The pod’s spec references that ServiceAccount and carries the same label on its own template — repeat the outfit, or the bouncer at the door won’t recognize you.</li></ol><p><strong>Runtime phase — every pod start, every call, no human involved</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9O0i9p7owFcKldsAc-fUjA.png" /></figure><ol><li>At pod startup, the webhook auto-injects AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_FEDERATED_TOKEN_FILE, AZURE_AUTHORITY_HOST, and mounts a short-lived, cluster-signed token — like slipping a hall pass under the door before anyone even asks for one.</li><li>DefaultAzureCredential() in app code finds these automatically and exchanges the projected token for a real Azure AD access token — no client ID, no secret, no connection string anywhere in code, no drama.</li><li>The app calls Service Bus and Key Vault with that token. The RBAC grants from step 4 decide what it’s allowed to do at each one, no arguing.</li></ol><p><strong>Nothing in this chain involves a stored secret.</strong> The only thing that ever moves is a token that expires in minutes and gets reissued automatically on the next request — the world’s most disposable hall pass.</p><h3>Where AKS actually connects to the identity</h3><p>Easy to gloss over, worth being precise about: <strong>the connection is one field</strong>. The federated credential’s issuer value is the cluster&#39;s OIDC issuer URL — that&#39;s the literal wire between AKS and the identity. Nothing else links them directly.</p><p>The client ID annotation on the Kubernetes ServiceAccount is a different, separate pointer — that’s the pod declaring which identity it wants to claim, not AKS-the-cluster connecting to anything.</p><h3>Where this actually breaks, ranked by how often it will happen to you</h3><ol><li><strong>Placeholder text left in the client ID annotation</strong> instead of the real GUID — Azure’s response to being handed &lt;your-client-id-here&gt; is AADSTS90013: Invalid input received from the user, which is Azure&#39;s polite way of saying &quot;that&#39;s not an ID, that&#39;s a note to yourself.&quot;</li><li><strong>Subject mismatch</strong> on the federated credential — must match system:serviceaccount:&lt;namespace&gt;:&lt;service-account-name&gt; exactly, character for character. Close enough is not a thing here; the bouncer does not do vibes-based ID checks.</li><li><strong>Missing label on the pod template</strong>, not just the ServiceAccount — the web hook is watching for a specific label and will not inject anything out of the goodness of its heart.</li><li><strong>RBAC scoped too high or too low</strong> — check the role assignment targets the actual queue or vault, not the whole namespace or subscription. Handing out subscription-wide access “just to get it working” is how incident reports get written.</li><li><strong>Fresh RBAC not yet propagated</strong> — role assignment changes can take a couple of minutes to take effect; a cold-start pod may fail its very first call, panic, and succeed fine on retry, like a nervous intern on their first day.</li></ol><h3>Quick reference</h3><p><strong>AKS OIDC issuer</strong> — the cluster’s own signer of trust tokens for its pods</p><p><strong>Managed identity</strong> — a password-less identity object in Entra ID</p><p><strong>Service principal</strong> — auto-created alongside the managed identity; what RBAC actually checks</p><p><strong>Federated identity credential</strong> — the trust rule linking the AKS issuer to the managed identity</p><p><strong>Role assignment (RBAC)</strong> — the grant: this principal, this role, this resource</p><p><strong>Resource ID</strong> — points the federated credential at the right identity</p><p><strong>Principal ID</strong> — what every RBAC check references</p><p><strong>Client ID</strong> — what the pod presents to authenticate at runtime</p><p><strong>DefaultAzureCredential</strong> — the app-side code that exchanges the pod&#39;s token for a real Azure AD token</p><h3>Now build it: the Terraform, step by step</h3><p>Everything above is the concept. Here’s the actual code, in the order it needs to go.</p><p><strong>1. Turn on the two AKS features that make this possible</strong></p><pre>resource &quot;azurerm_kubernetes_cluster&quot; &quot;aks&quot; {<br>  # ... rest of cluster config ...</pre><pre>  oidc_issuer_enabled       = true<br>  workload_identity_enabled = true<br>}</pre><p><strong>2. Create the identity — the blank ID card</strong></p><pre>resource &quot;azurerm_user_assigned_identity&quot; &quot;aks_console_app&quot; {<br>  name                = &quot;id-aks-console-app&quot;<br>  location            = azurerm_resource_group.rg.location<br>  resource_group_name = azurerm_resource_group.rg.name<br>}</pre><p><strong>3. Federate — the trust rule, pointed at the cluster’s issuer</strong></p><pre>resource &quot;azurerm_federated_identity_credential&quot; &quot;aks_console_app&quot; {<br>  name                = &quot;fic-aks-console-app&quot;<br>  resource_group_name = azurerm_resource_group.rg.name<br>  parent_id           = azurerm_user_assigned_identity.aks_console_app.id<br>  issuer              = azurerm_kubernetes_cluster.aks.oidc_issuer_url<br>  subject             = &quot;system:serviceaccount:dev:aks-console-app&quot;<br>  audience            = [&quot;api://AzureADTokenExchange&quot;]<br>}</pre><p>The subject line here is the one that has to match your Kubernetes YAML exactly — namespace dev, ServiceAccount aks-console-app, no typos allowed.</p><p><strong>4. Grant it access — Service Bus and Key Vault, scoped narrowly</strong></p><pre>resource &quot;azurerm_role_assignment&quot; &quot;aks_console_app_servicebus_receiver&quot; {<br>  scope                = azurerm_servicebus_queue.orders.id<br>  role_definition_name = &quot;Azure Service Bus Data Receiver&quot;<br>  principal_id         = azurerm_user_assigned_identity.aks_console_app.principal_id<br>}</pre><pre>resource &quot;azurerm_role_assignment&quot; &quot;aks_console_app_kv_secrets_user&quot; {<br>  scope                = azurerm_key_vault.kv.id<br>  role_definition_name = &quot;Key Vault Secrets User&quot;<br>  principal_id         = azurerm_user_assigned_identity.aks_console_app.principal_id<br>}</pre><p>Note scope on the first one — it&#39;s the queue itself, not the whole Service Bus namespace. That&#39;s the least-privilege choice paying off.</p><p><strong>5. Output the client ID, so you’re not digging through state later</strong></p><pre>output &quot;aks_console_app_client_id&quot; {<br>  value = azurerm_user_assigned_identity.aks_console_app.client_id<br>}</pre><h3>After terraform apply — the Kubernetes side</h3><p>Terraform builds the trust and the permissions. It doesn’t build the Kubernetes objects that actually claim them — that’s a separate, manual step.</p><p><strong>6. Point kubectl at the cluster</strong></p><pre>az aks get-credentials --resource-group &lt;rg&gt; --name &lt;aks_cluster_name&gt;</pre><p><strong>7. Create the namespace the federated credential expects</strong></p><pre>kubectl create namespace dev</pre><p><strong>8. Create the ServiceAccount, using the real client ID from the Terraform output</strong></p><pre>apiVersion: v1<br>kind: ServiceAccount<br>metadata:<br>  name: aks-console-app<br>  namespace: dev<br>  annotations:<br>    azure.workload.identity/client-id: &quot;&lt;value from terraform output aks_console_app_client_id&gt;&quot;<br>  labels:<br>    azure.workload.identity/use: &quot;true&quot;</pre><p><strong>9. Reference it from the Deployment, with the same label on the pod template</strong></p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: aks-console-app<br>  namespace: dev<br>spec:<br>  template:<br>    metadata:<br>      labels:<br>        azure.workload.identity/use: &quot;true&quot;<br>    spec:<br>      serviceAccountName: aks-console-app<br>      containers:<br>        - name: aks-console-app<br>          image: &lt;your registry&gt;/aks-console-app:latest</pre><p><strong>10. Verify the token got injected</strong></p><pre>kubectl exec -it &lt;pod-name&gt; -n dev -- env | grep AZURE</pre><p>You should see AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_FEDERATED_TOKEN_FILE, and AZURE_AUTHORITY_HOST. Missing any of them means the label or ServiceAccount name didn&#39;t line up somewhere above.</p><p><strong>11. Check it’s actually working</strong></p><pre>kubectl logs &lt;pod-name&gt; -n dev</pre><p>Success looks like: messages coming off the orders queue, and the Key Vault secret being read — no connection string, no client secret, anywhere in the deployment.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dbba6dd715be" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using C# Attributes to Power the Factory Pattern]]></title>
            <link>https://medium.com/@dotnetgik/using-c-attributes-to-power-the-factory-pattern-188496a2e149?source=rss-6003542fffd8------2</link>
            <guid isPermaLink="false">https://medium.com/p/188496a2e149</guid>
            <dc:creator><![CDATA[Mangesh Gaherwar]]></dc:creator>
            <pubDate>Sat, 13 Jun 2026 21:13:11 GMT</pubDate>
            <atom:updated>2026-06-13T21:13:11.455Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A cleaner, more extensible approach to object creation — no giant switch statements required</em></p><h3>The Problem with Traditional Factories</h3><p>If you’ve worked with the Factory pattern in C#, you’ve probably written something like this:</p><pre>public static INotificationSender CreateSender(string type) =&gt; type switch<br>{<br>    &quot;email&quot; =&gt; new EmailSender(),<br>    &quot;slack&quot; =&gt; new SlackSender(),<br>    &quot;sms&quot;   =&gt; new SmsSender(),<br>    &quot;push&quot;  =&gt; new PushSender(),<br>    _       =&gt; throw new ArgumentException($&quot;Unknown sender type: {type}&quot;)<br>};</pre><p>It works — until it doesn’t. Every new notification channel means touching the factory. Forget to update it and you get a runtime exception. This is an Open/Closed Principle violation hiding in plain sight: the factory is never truly <em>closed</em> for modification.</p><p>What if the senders could <em>register themselves</em>?</p><h3>The Idea: Let Attributes Do the Mapping</h3><p>C# custom attributes are metadata you attach to classes at compile time. Combined with reflection, they allow you to scan an assembly and discover types dynamically — without a central registry or switch statement.</p><p>The pattern works in four steps:</p><ol><li>Define a custom attribute that carries a key (e.g. &quot;email&quot;)</li><li>Decorate your concrete senders with it</li><li>Build a generic AttributeFactory&lt;TNotificationSender&gt; that scans assemblies and resolves via DI</li><li>Register everything cleanly with a single IServiceCollection extension</li></ol><h3>Step 1 — Define the Attribute</h3><pre>namespace AttributeFactory;</pre><pre>[AttributeUsage(AttributeTargets.Class, Inherited = false)]<br>public sealed class NotificationKeyAttribute : Attribute<br>{<br>    public string Key { get; }<br>    public NotificationKeyAttribute(string key) =&gt; Key = key;<br>}</pre><p>AttributeTargets.Class restricts it to classes only. Inherited = false ensures subclasses don&#39;t accidentally inherit a parent&#39;s key — an important safety detail.</p><h3>Step 2 — Define the Interface and Decorate Your Senders</h3><pre>namespace AttributeFactory;</pre><pre>public interface INotificationSender<br>{<br>    void Send(string message);<br>}</pre><p>Each sender gets decorated with [NotificationKey] and takes its dependencies through constructor injection:</p><pre>[NotificationKey(&quot;email&quot;)]<br>public class EmailSender : INotificationSender<br>{<br>    private readonly ILogger&lt;EmailSender&gt; _logger;<br>    public EmailSender(ILogger&lt;EmailSender&gt; logger) =&gt; _logger = logger;<br>    public void Send(string message) =&gt;<br>        _logger.LogInformation(&quot;[EMAIL] {Message}&quot;, message);<br>}</pre><pre>[NotificationKey(&quot;slack&quot;)]<br>public class SlackSender : INotificationSender<br>{<br>    private readonly ILogger&lt;SlackSender&gt; _logger;<br>    public SlackSender(ILogger&lt;SlackSender&gt; logger) =&gt; _logger = logger;<br>    public void Send(string message) =&gt;<br>        _logger.LogInformation(&quot;[SLACK] {Message}&quot;, message);<br>}</pre><pre>[NotificationKey(&quot;sms&quot;)]<br>public class SmsSender : INotificationSender<br>{<br>    private readonly ILogger&lt;SmsSender&gt; _logger;<br>    public SmsSender(ILogger&lt;SmsSender&gt; logger) =&gt; _logger = logger;<br>    public void Send(string message) =&gt;<br>        _logger.LogInformation(&quot;[SMS] {Message}&quot;, message);<br>}</pre><pre>[NotificationKey(&quot;push&quot;)]<br>public class PushSender : INotificationSender<br>{<br>    private readonly ILogger&lt;PushSender&gt; _logger;<br>    public PushSender(ILogger&lt;PushSender&gt; logger) =&gt; _logger = logger;<br>    public void Send(string message) =&gt;<br>        _logger.LogInformation(&quot;[PUSH] {Message}&quot;, message);<br>}</pre><p>Each class owns its own key. The factory doesn’t know about any of them — yet.</p><h3>Step 3 — The Generic Factory</h3><pre>public class AttributeFactory&lt;TNotificationSender&gt; where TNotificationSender : class<br>{<br>    private readonly IServiceProvider _provider;<br>    private readonly Dictionary&lt;string, Type&gt; _registry;</pre><pre>    public AttributeFactory(IServiceProvider provider)<br>    {<br>        _provider = provider;<br>        _registry = new Dictionary&lt;string, Type&gt;(StringComparer.OrdinalIgnoreCase);</pre><pre>        var assemblies = AppDomain.CurrentDomain.GetAssemblies().Where(a =&gt; !a.IsDynamic);<br>        foreach (var assembly in assemblies)<br>        {<br>            Type[] types;<br>            try<br>            {<br>                types = assembly.GetTypes();<br>            }<br>            catch (ReflectionTypeLoadException ex)<br>            {<br>                types = ex.Types.Where(t =&gt; t is not null).ToArray()!;<br>            }</pre><pre>            foreach (var t in types)<br>            {<br>                if (t is null) continue;<br>                if (!typeof(TNotificationSender).IsAssignableFrom(t) || !t.IsClass || t.IsAbstract) continue;<br>                var attr = t.GetCustomAttribute&lt;NotificationKeyAttribute&gt;();<br>                if (attr is null) continue;</pre><pre>                var key = attr.Key;<br>                if (_registry.TryGetValue(key, out var existing))<br>                    throw new InvalidOperationException(<br>                        $&quot;Duplicate product key &#39;{key}&#39; found on types &#39;{existing.FullName}&#39; and &#39;{t.FullName}&#39;.&quot;);</pre><pre>                _registry[key] = t;<br>            }<br>        }<br>    }</pre><pre>    public TNotificationSender Create(string key)<br>    {<br>        if (!_registry.TryGetValue(key, out var type))<br>            throw new KeyNotFoundException(<br>                $&quot;No notification sender registered for key &#39;{key}&#39;. Known keys: {string.Join(&quot;, &quot;, _registry.Keys)}&quot;);</pre><pre>        return (TNotificationSender)_provider.GetRequiredService(type);<br>    }</pre><pre>    public IReadOnlyCollection&lt;string&gt; RegisteredKeys =&gt; _registry.Keys.ToList().AsReadOnly();<br>}</pre><p>A few things worth noting here:</p><ul><li><strong>StringComparer.OrdinalIgnoreCase</strong> — so &quot;Email&quot; and &quot;email&quot; resolve to the same sender</li><li><strong>ReflectionTypeLoadException handling</strong> — gracefully skips assemblies that can&#39;t be fully loaded, which happens more often than you&#39;d think in real apps</li><li><strong>Duplicate key guard</strong> — throws at startup with a clear message if two classes share the same key</li><li><strong>RegisteredKeys</strong> — useful for debugging or exposing available channels via an API endpoint</li><li><strong>IServiceProvider.GetRequiredService</strong> — full DI support, so senders can take any constructor dependencies</li></ul><h3>Step 4 — Clean DI Registration</h3><p>The IServiceCollection extension wires everything up in one call:</p><pre>public static IServiceCollection AddAttributeFactory&lt;TNotificationSender&gt;(<br>    this IServiceCollection services,<br>    ServiceLifetime lifetime = ServiceLifetime.Transient)<br>    where TNotificationSender : class<br>{<br>    var implementations = new List&lt;Type&gt;();<br>    var assemblies = AppDomain.CurrentDomain.GetAssemblies().Where(a =&gt; !a.IsDynamic);</pre><pre>    foreach (var assembly in assemblies)<br>    {<br>        Type[] types;<br>        try { types = assembly.GetTypes(); }<br>        catch (ReflectionTypeLoadException ex)<br>        { types = ex.Types.Where(t =&gt; t is not null).ToArray()!; }</pre><pre>        foreach (var t in types)<br>        {<br>            if (t is null) continue;<br>            if (!typeof(TNotificationSender).IsAssignableFrom(t) || !t.IsClass || t.IsAbstract) continue;<br>            if (t.GetCustomAttribute&lt;NotificationKeyAttribute&gt;() is null) continue;<br>            implementations.Add(t);<br>        }<br>    }</pre><pre>    foreach (var type in implementations)<br>    {<br>        services.Add(new ServiceDescriptor(type, type, lifetime));<br>        services.Add(new ServiceDescriptor(typeof(TNotificationSender), type, lifetime));<br>    }</pre><pre>    services.AddSingleton&lt;AttributeFactory&lt;TNotificationSender&gt;&gt;();<br>    return services;<br>}</pre><p>And in your Program.cs:</p><pre>builder.Services.AddAttributeFactory&lt;INotificationSender&gt;();</pre><p>That single line registers all four senders — and any future ones — automatically.</p><h3>Using It</h3><pre>public class NotificationService<br>{<br>    private readonly AttributeFactory&lt;INotificationSender&gt; _factory;</pre><pre>    public NotificationService(AttributeFactory&lt;INotificationSender&gt; factory)<br>        =&gt; _factory = factory;</pre><pre>    public void Notify(string channel, string message)<br>    {<br>        var sender = _factory.Create(channel);<br>        sender.Send(message);<br>    }<br>}</pre><pre>notificationService.Notify(&quot;email&quot;, &quot;Your order has shipped!&quot;);<br>notificationService.Notify(&quot;slack&quot;, &quot;Deployment succeeded ✅&quot;);<br>notificationService.Notify(&quot;sms&quot;,   &quot;Your verification code is 4521&quot;);<br>notificationService.Notify(&quot;push&quot;,  &quot;You have a new message.&quot;);</pre><p>Need to add a WhatsApp channel tomorrow?</p><pre>[NotificationKey(&quot;whatsapp&quot;)]<br>public class WhatsAppSender : INotificationSender<br>{<br>    private readonly ILogger&lt;WhatsAppSender&gt; _logger;<br>    public WhatsAppSender(ILogger&lt;WhatsAppSender&gt; logger) =&gt; _logger = logger;<br>    public void Send(string message) =&gt;<br>        _logger.LogInformation(&quot;[WHATSAPP] {Message}&quot;, message);<br>}</pre><p>Zero changes to the factory. Zero changes to Program.cs. It just works.</p><h3>Pros</h3><p><strong>✅ Open/Closed Principle in practice</strong> New notification channels extend the system without modifying the factory. This is OCP working exactly as intended.</p><p><strong>✅ Self-registering types</strong> Each sender owns its own key. The knowledge of <em>how to register</em> lives next to the class itself — not in a central file someone has to remember to update.</p><p><strong>✅ Full DI support</strong> Because resolution goes through IServiceProvider, senders can take any constructor dependencies — loggers, HTTP clients, configuration, you name it.</p><p><strong>✅ Case-insensitive keys</strong> StringComparer.OrdinalIgnoreCase means &quot;Email&quot;, &quot;email&quot;, and &quot;EMAIL&quot; all resolve correctly without any extra handling.</p><p><strong>✅ Configurable lifetime</strong> AddAttributeFactory&lt;INotificationSender&gt;(ServiceLifetime.Scoped) gives you full control over how senders are instantiated per request.</p><p><strong>✅ Scales cleanly</strong> Whether you have 4 channels or 40, the factory and registration code stay identical.</p><h3>Cons</h3><p><strong>⚠️ Reflection has a cost</strong> Assembly scanning is not free. The good news: AttributeFactory&lt;TNotificationSender&gt; is registered as a Singleton, so scanning happens exactly once at startup. At runtime, Create() is just a dictionary lookup.</p><p><strong>⚠️ No compile-time safety on keys</strong> _factory.Create(&quot;emial&quot;) compiles fine and fails at runtime. Consider using const strings to centralise your keys:</p><pre>public static class NotificationChannels<br>{<br>    public const string Email = &quot;email&quot;;<br>    public const string Slack = &quot;slack&quot;;<br>    public const string Sms   = &quot;sms&quot;;<br>    public const string Push  = &quot;push&quot;;<br>}</pre><p><strong>⚠️ Harder to trace statically</strong> Tools like Find All References won’t show every class registered under a given key. The loose coupling that makes it extensible also makes it less obvious at a glance — worth documenting for your team.</p><h3>When to Use This Pattern</h3><p><strong>✅ Use it when:</strong></p><ul><li>You have many implementations of one interface</li><li>New channels are added frequently</li><li>Senders need constructor injection</li><li>You want zero changes to the factory</li></ul><p><strong>❌ Avoid it when:</strong></p><ul><li>You only have 2–3 concrete types</li><li>The set of senders is fixed and stable</li><li>You want zero reflection at runtime</li><li>Startup scan time is a hard constraint</li></ul><h3>Wrapping Up</h3><p>The Attribute-driven Factory pattern is a simple but powerful technique. It shifts the registration responsibility from a central switch statement to the senders themselves — making your factory genuinely open for extension and closed for modification.</p><p>The generic AttributeFactory&lt;TNotificationSender&gt; makes this reusable beyond notification senders too. Payment providers, report exporters, file parsers — any interface with multiple implementations is a candidate.</p><blockquote><em>💡 The full source code is available on GitHub: </em><a href="https://github.com/dotnetgik-lgtm/MyPetProjects/tree/main/AttributeFactory"><em>AttributeFactory — MyPetProjects</em></a></blockquote><p><em>Found this useful? Follow me for more practical .NET patterns.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=188496a2e149" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[gRPC with C# and .Net Core — Part 1]]></title>
            <link>https://medium.com/@dotnetgik/grpc-with-c-and-net-core-part-1-677e8b6ea0d3?source=rss-6003542fffd8------2</link>
            <guid isPermaLink="false">https://medium.com/p/677e8b6ea0d3</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[grpc]]></category>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[wcf]]></category>
            <dc:creator><![CDATA[Mangesh Gaherwar]]></dc:creator>
            <pubDate>Thu, 19 Dec 2019 15:03:02 GMT</pubDate>
            <atom:updated>2020-07-28T10:20:17.034Z</atom:updated>
            <content:encoded><![CDATA[<h3>gRPC with C# and .Net Core</h3><p>Net Core 3.0 has been launched last month and one of the major features of it is gRPC. Let’s have a detailed discussion on how to get started with gRPC using C# and .Net Core. Let’s divide our article into the following sections, <strong>Agenda</strong></p><ol><li>What is GRPC</li><li>GRPC Vs REST</li><li>Creating GRPC Service</li><li>Creating GRPC Client</li><li>WCF to GRPC</li><li>Conclusion</li></ol><h3>What is gRPC</h3><p>According to official blog “GRPC is a open source high performance RPC framework that can run in any environment, it can efficiently connect services across data centers with support of load balancing, tracing and authentication.” Mostly gRPC is used for connecting polyglot services in microservices architecture, connecting mobile devices, browser clients to the services Grpc has two parts the — gRPC protocol and data serialization. By default gRPC uses Protobuf for the serialization and protocol is based on Http2 which provides a lot of advantages over traditional Http1.x</p><h3>GRPC vs REST</h3><p>REST has been one of the concrete pillars of the web programming recently, but the emergence of the gRPC has put some challenge before REST. The below tables explain the differences between them,</p><h3>Creating GRPC Service</h3><p>As we are good with the basics, for now, let’s move and see how we can create the Service, and later let’s see how we can consume that service into the client. To get started with the service we need to have a few initial things as follows</p><p>Once you have this we can follow the following steps to create our first service</p><p><strong>Add New Project and Select the GRPC Service as a new project</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/0*Mlff2bpdSJfRk1bm" /></figure><p>In our case, we are adding a Project with name ToDoGrpcService, when we will add the Project we will have the following Structure,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/361/0*EYFG_p4e4_3aJe3I" /></figure><p>Our project will be added with the default Greet service and One Default <em>greet. Proto</em> File. In this project, we are going to create our first To-do. Grpc Service for that first we need to add the proto file like below. Right Click on Protos Folder -&gt; Add New Item -&gt; Select ProtoBuff File and name it “ToDo” like below,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/0*kdDupyBBzJriVHmk" /></figure><h3>Creating ProtoBuff Service Contract and Schema</h3><p>Grpc uses Proto File to define the service contracts and it also contains the schema for the data which will be sent across between the services. Our ToDo service will have the following code,</p><pre>syntax = &quot;proto3&quot;; <br>option csharp_namespace = &quot;ToDoProtos&quot;; </pre><pre>service ToDoService{ <br>rpc getToDoItem(google.protobuf.Empty) <br>returns (ToDoModel); <br>}<br> <br>message ToDoModel<br>{ string Title=1;<br>  string Description=2;<br>  bool status=3; <br>}</pre><p><strong>Code Explanation</strong></p><ol><li>The first line specifies the version of Protobuff used in the programs; i.e. Proto3</li><li>The second line specifies the Namespace under which this service will be created</li><li>The next section specifies the actual service name and the Method into the Service. In our case our service is ToDoService and we have getToDoItem Method with empty parameter and returns the ToDoModel</li><li>The last section is the actual data which will be returned from the service</li></ol><h3>Creating Server</h3><p>Once we are done with adding the proto buff file we are ready to create the server. In this server, we will use the automatically generated code from the protobuff file. We can stub out the functionality over the code which handles the communication and serialization. To generate the code from the protobuf file we need to make the changes in the .csproj file of our project and add lines like below,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*81ZDsmpclV_Nc58O" /></figure><h3>Implementing the Service</h3><p>The next step in creating service is to create a class that will be inherited from the above-generated class and implements the service contract that we have defined in the protobuff file above. Once implemented it will look like below</p><pre>using System;<br>using System.Collections.Generic;<br>using System.Linq; <br>using System.Threading.Tasks;<br>using Google.Protobuf.WellKnownTypes;<br>using Grpc.Core;<br>using ToDoProtos;<br>namespace SampleGrpcService.Services <br>{<br>public class ToDoDataService: ToDoProtos.ToDoService.ToDoServiceBase {<br> public override Task&lt;ToDoModel&gt; getToDoItem(Empty request, ServerCallContext context) <br>{ return Task.FromResult(GetToDoData()); }<br> public ToDoModel GetToDoData() <br>{<br> return new ToDoModel() { Status = true, Description = &quot;First Grpc Service&quot;, Title = &quot;Grpc Service&quot; }; <br>} <br>}<br>}</pre><p>This will complete our steps for the creation of our first grpc service. Now it’s time to create a client that will consume this service and show us the output. Before that let’s run the application using console using command <em>dotnet Run</em></p><h3>Startup and Configure Services changes</h3><p>After making changes in the startup section the code will look like below. In this, we have to map our endpoints to the services which we have generated and we have to tell the application that we are going to use the grpc as a service in the application.</p><pre>public void ConfigureServices(IServiceCollection services) <br>{<br> services.AddGrpc();<br> }<br> public void Configure(IApplicationBuilder app, IWebHostEnvironment env)<br> { <br>if (env.IsDevelopment())<br> { <br> app.UseDeveloperExceptionPage(); <br> } <br>app.UseRouting();<br>app.UseEndpoints(endpoints =&gt; <br>{ <br>endpoints.MapGrpcService&lt;GreeterService&gt;(); endpoints.MapGrpcService&lt;SampleGrpcService.Services.ToDoDataService&gt;(); <br>endpoints.MapGet(&quot;/&quot;, async context =&gt; <br>{ <br>await context.Response.WriteAsync(&quot;Communication with gRPC endpoints must be made through a gRPC client. To learn how to create a client, visit: https://go.microsoft.com/fwlink/?linkid=2086909&quot;); <br>}); <br>}); <br>}</pre><h3>Creating Client</h3><p>To create a client let’s add the console application like usual. Once the application is added let’s add following three packages in the project,</p><p>The next thing that we need to do in the client project is to add the Proto file that we have generated already. Again we have to modify .csproj file to generate a stub for the client code that we want to use in the application like below</p><pre>&lt;ItemGroup&gt; &lt;Protobuf Include=&quot;Protos\ToDo.proto&quot; GrpcServices=&quot;Client&quot; /&gt; &lt;/ItemGroup&gt;</pre><p>The next step is to add the client code which will call the service. The code will be like below in which we create a channel pointing to an address where our service will be hosted and next we will have a client-generated from the proto file. It will have a Method which will be called just like we call a class Method.</p><pre>using System; <br>namespace TodoGrpcClient<br> {<br> class Program <br>{ <br>static void Main(string[] args) <br>{ <br>var channel = Grpc.Net.Client.GrpcChannel.ForAddress(&quot;https://localhost:5001/&quot;); var client = new ToDoProtos.ToDoService.ToDoServiceClient(channel); var request = new Google.Protobuf.WellKnownTypes.Empty(); var result = client.getToDoItem(request); Console.WriteLine(result.Description); Console.WriteLine(result.Status); Console.WriteLine(result.Title); Console.ReadKey(); <br>} <br>} <br>}</pre><p>Just set the client project as a startup project and run the application and we can see the output as below,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/0*wnNp1AllW2L_J1ss" /></figure><p>This was all about creating the client for the Grpc Service</p><h3>WCF to GRPC</h3><p>One of the alternatives as recommended by Microsoft is to use the Grpc instead of the WCF services in future projects. In this section, let us see how we can relate our understanding of the WCF to the Grpc concepts that we have right now,</p><h3>Conclusion</h3><p>This was all about creating your first Grpc Service using C# and Asp.net core. You can find the code attached to the article for you</p><p>. <strong>References</strong></p><ol><li><a href="https://docs.microsoft.com/en-us/dotnet/architecture/grpc-for-wcf-developers/"><em>https://docs.microsoft.com/en-us/dotnet/architecture/grpc-for-wcf-developers/</em></a></li><li><a href="https://docs.microsoft.com/en-us/aspnet/core/grpc/?view=aspnetcore-3.0"><em>https://docs.microsoft.com/en-us/aspnet/core/grpc/?view=aspnetcore-3.0</em></a></li><li><a href="https://grpc.io/docs/guides/"><em>https://grpc.io/docs/guides/</em></a></li></ol><p><em>Originally published at </em><a href="https://dotnetgik.com/grpc-with-c-and-net-core-part-1/"><em>http://dotnetgik.com</em></a><em> on December 19, 2019.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=677e8b6ea0d3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>