avatarNicklas Millard

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

2945

Abstract

d="02f3">Anyway… Simply put it’s a three step process</p><ol><li>We derive a type based on the ICommand interface and the generic method argument</li><li>Find any concrete classes that implements the interface ICommandHandler<tcommand></tcommand></li><li>Invoke “Handle” on the concrete handler class</li></ol><h2 id="1ecf">How it works</h2><p id="1cd1">On line 7 we get a type called <code>BookStore.Application.ICommandHandler1[TCommand]</code>. BookStore.Application is just the name of the assembly (.dll) that the ICommand interface lives in.</p><p id="759f">If you’re new to generics, then this reads as “ICommandHandler of TCommand”.</p><p id="03a0">You see, this is not specific enough for us to use. We need the TCommand to not be generic, but instead be of a concrete type.</p><p id="4a24">If we for instance call the Dispatcher using the <code>CreateAuthorCommand</code>, we’ll need to derive a type that replaces the <code>TCommand</code> with a concrete type. We do this on line 8 by calling <code>.MakeGenericType(command.GetType())</code>. This effectively replaces ICommand with the command type passed in.</p><p id="5f78">Now, on line 11 we search for any concrete classes that implements the type <code>ICommandHandler&lt;CreateAuthorCommand&gt;</code>.</p><p id="682b">On line 18–20 we loop thru the list of found classes that implements the target interface, and try to instantiate the class. <code>Activator.CreateInstance()</code>` just calls the parameterless constructor of the class.</p><p id="f51e">On line 22 we try to call the Handle class that we know the object will have, because it implements the interface ICommandHandler.</p> <figure id="9442"> <div> <div> <img class="ratio" src="http://placehold.it/16x9"> <iframe class="" src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FdXF60OlMgYU%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DdXF60OlMgYU&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FdXF60OlMgYU%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" allowfullscreen="" frameborder="0" height="480" width="854"> </div> </div> </figure></iframe></div></div></figure><h2 id="5bc2">Creating new handlers</h2><p id="83b8">It’s as simple as creating a new class that implements the ICommandHandler<createauthorcommand> interface.</createauthorcommand></p><p id="36e9">That’s it.</p><p id="1b23">Any new handler will be picked up by the Dispatcher automatically due to the reflection we’ve used.</p><p id="523d">🔔 <a href="https://nmillard.medium.com/subscribe">Want more articles like this? Sign up here.</a></p><h1 id="b1e0">What about dependency injection?</h1><p id="ace9">You’ve probably already noticed that there’s a problem having the Activator only invoking the d

Options

efault, parameterless constructor, right?</p><p id="c2cb">What if your handlers need dependencies, such as a repository, email sender, or whatever?</p><p id="f0a4">To solve this problem, I’ve just injected a DI container into the dispatcher’s constructor, and performed same same search for any registered types that implements the appropriate interface.</p><figure id="fac8"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*TMZihqPx2zFjYDyIZ5tKTQ.png"><figcaption></figcaption></figure><div id="db95" class="link-block"> <a href="https://readmedium.com/stop-using-if-else-statements-f4d2323e6e4"> <div> <div> <h2>Stop Using If-Else Statements</h2> <div><h3>Write clean, maintainable code without if-else.</h3></div> <div><p>medium.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/1*xUWTgHxBR4P_lYWzqGgImQ.png)"></div> </div> </div> </a> </div><div id="89f2" class="link-block"> <a href="https://readmedium.com/stop-checking-for-nulls-5f9f857ddf72"> <div> <div> <h2>Stop Checking for Nulls</h2> <div><h3>Null Object Pattern, Factory Methods — Let’s see some production ready code!</h3></div> <div><p>medium.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/1*PEkfn8OvgbNMSrHUPVIYUQ.png)"></div> </div> </div> </a> </div><div id="d7ce" class="link-block"> <a href="https://levelup.gitconnected.com/forget-about-constructors-8fb61288065"> <div> <div> <h2>Forget About Constructors</h2> <div><h3>Let’s use an alternative approach to object instantiation</h3></div> <div><p>levelup.gitconnected.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/1*b8swGL50LNjMKIlsJXdzEg.png)"></div> </div> </div> </a> </div><h1 id="5bd9">Let’s stay in touch!</h1><p id="58a7"><a href="https://nmillard.medium.com/subscribe">Get notified about similar articles by signing up for the newsletter here</a> and check out the <a href="https://www.youtube.com/channel/UCaUy83EAkVdXsZjF3xGSvMw"><i>YouTube Channel (@Nicklas Millard)</i></a><i>.</i></p><p id="abf5"><a href="https://www.linkedin.com/in/nicklasmillard/">Connect on LinkedIn</a>.</p><h1 id="8008">Are you a technical hiring manager?</h1><p id="1415">Then check out<a href="https://devcays.com/"> Devcays.com</a> for real-world code cases you can use when interviewing .NET developers!</p></article></body>

PRACTICAL PROGRAMMING ADVICE

Dynamic Command Dispatching In C#

Let’s keep this one short and sweet

So you’ve heard of the Open/Closed principal of SOLID — and Command Query Separation. But you’re not completely onboard with how to actually do this in practice.

Also, you’re aware that it’s considered a violation of OCP if you have to modify an existing class to accommodate new behaviour. The desired action would be to just create a new class that implements the new behaviour or functionality you’d like to add to the application.

In this article we’ll achieve the following

👉🏼 Dispatch commands that will be handled by some other “handler” class 👉🏼 Add new commands without modifying existing classes 👉🏼 Dynamically invoke handlers when a command is dispatched

🔔 Want more articles like this? Sign up here.

It’s all about interfaces

First, we’ll create a contract (interface) that handlers must adhere to.

ICommandHandler` simply requires the implementing class to expose a method called “Handle” which takes an argument of whatever type “TCommand” is. The only constraint is TCommand must be a class.

Here’s an example of a class that implements the ICommandHandler interface. We’re just writing out some text.

If you’re curious about the CreateAuthorCommand`, it looks like this

With the foundations in place, we’ll move on to what it’s all about: dynamically dispatching commands and allowing us to extend the application as much as we want.

Creating the dispatcher

We’ll have a so-called dispatcher — name it whatever you want — that will have the responsibility of receiving a command and find appropriate handler(s) for that specific command.

If you’re not used to reflection, this might look like greek to you. However, this is a must if you want to know how to add functionality without modifying existing classes.

Anyway… Simply put it’s a three step process

  1. We derive a type based on the ICommand interface and the generic method argument
  2. Find any concrete classes that implements the interface ICommandHandler
  3. Invoke “Handle” on the concrete handler class

How it works

On line 7 we get a type called BookStore.Application.ICommandHandler`1[TCommand]`. BookStore.Application is just the name of the assembly (.dll) that the ICommand interface lives in.

If you’re new to generics, then this reads as “ICommandHandler of TCommand”.

You see, this is not specific enough for us to use. We need the TCommand to not be generic, but instead be of a concrete type.

If we for instance call the Dispatcher using the CreateAuthorCommand`, we’ll need to derive a type that replaces the TCommand` with a concrete type. We do this on line 8 by calling .MakeGenericType(command.GetType())`. This effectively replaces ICommand with the command type passed in.

Now, on line 11 we search for any concrete classes that implements the type ICommandHandler<CreateAuthorCommand>`.

On line 18–20 we loop thru the list of found classes that implements the target interface, and try to instantiate the class. Activator.CreateInstance()` just calls the parameterless constructor of the class.

On line 22 we try to call the Handle class that we know the object will have, because it implements the interface ICommandHandler.

Creating new handlers

It’s as simple as creating a new class that implements the ICommandHandler interface.

That’s it.

Any new handler will be picked up by the Dispatcher automatically due to the reflection we’ve used.

🔔 Want more articles like this? Sign up here.

What about dependency injection?

You’ve probably already noticed that there’s a problem having the Activator only invoking the default, parameterless constructor, right?

What if your handlers need dependencies, such as a repository, email sender, or whatever?

To solve this problem, I’ve just injected a DI container into the dispatcher’s constructor, and performed same same search for any registered types that implements the appropriate interface.

Let’s stay in touch!

Get notified about similar articles by signing up for the newsletter here and check out the YouTube Channel (@Nicklas Millard).

Connect on LinkedIn.

Are you a technical hiring manager?

Then check out Devcays.com for real-world code cases you can use when interviewing .NET developers!

C Sharp Programming
Dotnet
Dotnet Core
Cqrs
Solid
Recommended from ReadMedium