SHARE:

Duck casting in C# with Impromptu Interface, example with ASP.NET Core

Introduction

First, “duck casting” is not “duck typing”. For those who want to know more about “duck typing” a very good link is available here: https://ericlippert.com/2014/01/02/what-is-duck-typing/. In this article I’m talking about “duck casting”, a technique that allows to use any dynamic object as typed object by an explicit casting (if the signature of the object is the same). I will use Impromptu Interface to show how we can achieve this kind of casting and give example in ASP.NET Core to demonstrate why this technique could be useful.

Scenario

Let’s consider a repository that you inherit from a legacy layer for example. The repository takes in parameter of its constructor an interface named IConfig. This interface has a ConnectionString property :

Now we want to use this repository, but we don’t want at all to create a class that implement this IConfig interface. In this case it’s absolutely ridiculous to create a class with only one property and used only once within a single repository (this scenario may happen often in a microservices architecture)

Impromptu Interface in action

Before starting coding, let’s download the package:

PM> Install-Package ImpromptuInterface -Version 7.0.1 

We are using an ASP.NET Core WebAPI an we have to use Dependency Injection so we need to configure our repository in the Startup.cs file in consequence. How can we use Impromptu Interface here? Simple! We just need to create an anonymous object that has the same signature as IConfig interface and cast it into this type with the method ActLike<IConfig> where you usually declare your services:

Let’s execute the code!

Beautiful and convenient isn’t it? 😉

Written by

anthonygiretti

Anthony is a specialist in Web technologies (14 years of experience), in particular Microsoft .NET and learns the Cloud Azure platform. He has received twice the Microsoft MVP award and he is also certified Microsoft MCSD and Azure Fundamentals.
%d bloggers like this: