How to configure StructureMap to inject a typed logger

Logging is an essential part of every application. Might be dead simple as Console.WriteLine() or a complex third party library but every piece of software needs a way to communicate its status.

In my last project I have decided to use the wonderful NLog . One of the good things this library has is the possibility to add some contextual information to the messages, including (by default) the name of the calling class. Something like this:

2017-10-06 17:01:06.0417|INFO|MyAwesomeProgram.MyAwesomeClass|This is my message

As you can see, I have outlined with different colors the level, the name of the caller and the text.

This can be easily accomplished by something like this:

Using a static cTor to init the logger helps to  get a better stack trace in case GetCurrentClassLogger() throws an exception for some reason.

However, in case you’re using a DI container (as you should), it may become complicate to inject a valid Logger instance into each class.

Getting back to my project, for this I am using StructureMap as DI container. Usually I tend to stick with Simple Injector, but I just joined the team and it’s very important to follow the existing conventions.

The idea here is to use a wrapper class around the logger instance that takes as cTor parameter the name of the calling class. I’m using a wrapper just to avoid coupling with a third party library: usually you wouldn’t change from a logging library to another unless you’ve a very good reason for, but this principle applies basically to anything.

Next step is to configure StructureMap to return each time a new instance of the LoggerWrapper with the proper calling class name. And that’s actually the easy part!
Here’s the full code:

As you can see the magic happens during the StructureMap setup: context.ParentType represents the type of the class that will receive the LoggerWrapper instance.


Now let’s take a step back. Logging falls into the category of “cross-cutting concerns” , which basically means that logging can be considered part of the “infrastructure” and of course not of the business logic of the application. Caching can be another good example.

That said, unless you really need to  write specific log messages in specific points of your application, another option could be using the Decorator pattern . The idea is pretty straightforward:

  1. create a FooLoggingDecorator class
  2. inject the logger
  3. wrap all the class methods
  4. add logging where needed

Now it’s up to you to decide which approach to take, they both have pros and cons. For example, injecting the logger in some case can imply a SRP violation. On the other hand, using a decorator requires wrapping all the inner class methods. Keep that in mind when you add stuff to your interfaces 🙂

As Jeremy wrote in his comment, the StructureMap documentation suggests to use a logger convention instead which would  be (quoting):

“significantly more efficient at runtime because the decision about which Logger to use is only done once upfront” 

How to detect current culture in javascript

Detecting the current culture in javascript can be really useful in many cases, for example when you have a dropdown with the list of languages and you want the user’s preferred one already selected.

I am getting a little lazy these days, I would like to write more articles about software architecture, design patterns or fancy techs like MongoDb and so on…. but I am moving to another country and packing an entire house is taking away all my time and energies.

So this is just a quick post showing a couple of ways to detect the current culture in javascript. Probably just a reminder for my sloppy memory 🙂

Based on the docs on the MDN website, the window.navigator object exposes a language property that represents  the preferred language of the user, usually the language of the browser UI. 

The compatibility is quite good except as usual for IE Mobile, however there are two valid alternatives, userLanguage and browserLanguage.

In case you want the list of all the preferred languages for the user, there’s an experimental property you can exploit, navigator.languages. That’s an “experimental technology”, so the compatibility list is still short (eg. Chrome and Firefox, as usual). It’s a string array containing the list of the user’s preferred languages, with the most preferred language first. 

Based on the docs, navigator.language should be the first element of the returned array but if I check the values in Chrome I get this:

navigator.languages -> [“it-IT”, “it”, “en-US”, “en”]
navigator.language -> “en-GB”

Weird, isn’t it?

My guess is that navigator.languages returns the list of the user system preferred languages, while navigator.language gives instead the current browser’s language. 

Searching on StackOverflow there’s a good answer to the question, I have extracted the code in this gist (link in the code):


Free Microsoft eBook giveaway!

A friend of mine just pointed me to a very interesting link that I think it’s worth sharing: 
It’s from the Eric Ligman blog on MSDN, he’s sharing a HUGE list of Microsoft eBooks about basically everything, from Azure to Office, to Powershell to .NET development.

I have started with Machine Learning on Azure since it is a huge hype these days and I definitely need to give it a try.

I have been reading also a lot about Microservices lately and I’m still waiting my good friend and colleague Lalit to sign me a copy of his book .

Another thing I am investigating is Xamarin. Personally I am not a huge fan of mobile applications, I believe “standard” web development will replace native apps (maybe not cpu/gpu intensive applications like games for example) but I also believe that is good to have at least a minimal knowledge of it. 

In any case, if you enjoy reading or you’re just curious, don’t miss it!

How to create a docker container for a WordPress website

This is my first post on Docker so please be gentle. I am going to start with something easy: how to create a Docker container to host a WordPress website.

One word before we start: don’t do this on a production server! There are more rules and checks you have to do, this is just an introduction, good for a dev/demo environment.

So, I assume you already have docker and docker-compose installed on your system, but in case you don’t, there’s an excellent documentation on the Docker’s website.

The first step is to fire up the terminal, create a folder and save the contents of this gist to a file named docker-compose.yml .

Next step is to fire up the containers with this command:

docker-compose up -d

the -d is the “detached mode”, allows you to run the containers in background and keep using the terminal.

Now, if you take a look at our Compose configuration, on line 22 we have specified an host address for the mysql instance. It might be already correct, but better check. 
From the command line, first run

docker ps

to get the list of running containers. You should see something like this:

using docker ps to get the list of containers

using docker ps to get the list of containers

Grab the name of the db container and run

docker inspect wptestfull_mysql_1

You will get a big JSON object exposing the status and all the available properties of the container. At the end you should get this:

using docker inspect to get the container ip address

using docker inspect to get the container ip address

there you go, our IPAddress. Copy it into the docker-compose file and run again docker-compose up -d .

Now we need to create a db user. Open your browser and go to http://localhost:8181/ , you will see the phpMyAdmin interface. Create the user, the db and set the allowed hosts to % . This way we will allow connections from every address. Again: don’t do this on production!

Now all you have to do is to load http://localhost:8080/ and setup your WordPress instance 🙂

Next time: what if we want more than one website?

Don’t worry, Heimdall will watch over all your microservices.

TL;DR : I wrote a service registry tool, named Heimdall, go and fork it!

Long version: almost every time I am working on a piece of code I get stuck on something and after a while I get new ideas for new projects. This may lead to a huge number of useless git repos, each one with a partially functional software, but it also pushes me to work on new things each day.

This time I was working on a super-secret project (that I will of course share very soon) based on a nice microservices architecture and I soon realized I needed some kind of Service Registry. The project was quite small so I was not really interested in a complex tool like a router with load balancing functions or similia so I decided to code the thing myself.

For the ones of you that don’t know what a Service Registry is and what it does, allow me to give you some context.
Imagine you’re a client that needs to consume some APIs. You could of course use a configuration file for storing the endpoints but in case you’re cloud-based, urls can change often.

Also, what if you want some nice features like multiple instances, autoscaling and load balancing?

The answer is simple: use a registry! 

Every service will register itself during initialization, allowing clients to query the registry and know the endpoint (possibly the best one).

I found this concept pretty useful so I decided to create a poor man’s version myself, using ASP.NET Core, MongoDB and React and I named it Heimdall, the guardian god of the Norse mythology .
The list of features for now is very scarce, you can just register a service, add/remove endpoints and query, but I have a full roadmap ready 🙂

Oh and I also added help pages using Swagger !

© 2017 Davide Guida

Theme by Anders NorenUp ↑