Category.NET

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 🙂

[EDIT]
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” 

Free Microsoft eBook giveaway!

A friend of mine just pointed me to a very interesting link that I think it’s worth sharing: https://blogs.msdn.microsoft.com/mssmallbiz/2017/07/11/largest-free-microsoft-ebook-giveaway-im-giving-away-millions-of-free-microsoft-ebooks-again-including-windows-10-office-365-office-2016-power-bi-azure-windows-8-1-office-2013-sharepo/ 
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!

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 !

Command Handlers return values in CQRS

I have recently came across this very interesting blog post by Jimmy Bogard ( the guy behind Mediatr, if you don’t know him). Talking about CQRS, he makes a good point about how the user should be informed of the result of a Command execution.

Should the Command Handler return a value?
Should the Command Handler throw an exception?

These are just some of the strategies we may take, another option could be just logging the operation and forget anything happened. Whatever.

A while ago I blogged about how to validate the Commands and ensure the data passed to the Command Handler is valid. This is the strategy I’m adopting in my projects lately. Why? Several reasons: first of all I want to keep Command execution separated from the validation, also Commands should be some sort of “fire and forget” operations. Let me clarify this a little bit.
In my opinion Command execution should be a boolean operation: the system can either execute it or not. Stop. I should be able to know ahead if a Command can be executed and that’s the validation phase. If I finally manage to get to the Handler, I know that the data I have is valid and I can run Command. No need to return a “true”.

So what should I do to make all the pieces fit?

  1. Use the Decorator pattern to ensure each Command Handler executes some sort of validation
  2. Analyze the Command and check its validity against business rules or anything else you want
  3. the Validator gives back a Validation result containing a (hopefully empty) list of errors
  4. in case something went wrong, throw a specialized Exception, for example something like this

Since most of the projects I am working on lately is composed of some sort of Web API based on .NET Core, I decided to create an Exception Filter that will eventually return to the user a JSON object with the details of the validation.

 

Bonus
Some of you may have noticed that some of the links in this post point to this Github repository, LibCore. It’s a small set of utilities I am writing, mantaining and using in my projects. I thought it would be useful to share the sources, maybe just to hear comments from the community. Food for thought.

Unit testing MongoDB in C# part 4: the tests, finally

More than a year. Wow, that’s a lot, even for me! In the last episode of this series we discussed about how to create the Factories for our Repositories. I guess now it’s time to put an use to all those interfaces and finally see how to unit test our MongoDB repositories 🙂

Remember: we are not testing the driver here. The MongoDB team is responsible for that. Not us. 

What we have to do instead is to make sure all our classes follow the SOLID principles and are testable. This way we can create a fake implementation of the low level data access layer and inject it in the classes we have to test. Stop.

Let’s have a look at the code:

In our little example here I am testing a CQRS Command Handler, the one responsible for creating a user. Our handler has an IDbContext as dependency, which being an interface allows us to use the Moq Nuget package to create a fake context implementation. 

Also, we have to instruct the mockDbContext instance to return a mock User Repository every time we access the .Users property.

At this point all we have to do is to create the sut, execute the method we want to test and Verify() our expectations. 

Let’s make a more interesting example now:

Now that we have created the user, we may want also to update some of his details. The idea here is to instruct the mockRepo instance to return a specific user every time the FinstOneAsync method is executed.

Again, now we just need to verify the expectations and we’re done!

Note that in this case we are making an assumption about the inner mechanism of the Handle() method of the UpdateUserHandler class. Personally I tend to stick with Black Box Testing, but sometimes (eg. now) you might be forced to use White Box Testing instead. If you don’t know what I am talking about, there’s a nice article here you may want to read.

 

© 2017 Davide Guida

Theme by Anders NorenUp ↑