August 9

Moq phoning home with/to SponsorLink? What to do about it.

Hopefully you've heard about the latest changes to a popular Open Source Software Project used by the .NET ecosystem. No? Well here is some reading material:

This issue in Moq's GitHub repo has more information as well. how do you handle this? I'm sure most of us out there in the world have other projects in flight and don't want to end up accidently pulling in this problematic NuGet package. Most clients/project managers/projects don't respond well to having to stop active development on a dime just to refactor a bunch of test code. So what do we do? Microsoft has us covered in this scenario. In this case we only want to allow Moq v4.18.4. We will come back later on when we have time to refactor/replace Moq. Let's consult the docs shall we?

In the beginning we see that we have Moq v4.18.4 installed and there is an update to v4.20.2.

We need to go through our solution and replace each PackageReference for Moq in each project that uses it. So we're going from this:

<PackageReference Include="Moq" Version="4.18.4" />

to this:

<PackageReference Include="Moq" Version="[4.18.4]" />
After changing all the PackageReferences for Moq in the solution, you'll notice that the package is no longer showing up in the Updates tab.

Is this foolproof? No, you can still update the Moq package. By removing the option in the Updates tab, you will have removed the temptation to update it.

Category: .NET, unit testing | Comments Off on Moq phoning home with/to SponsorLink? What to do about it.
August 3

Registering Types With the SimpleIoC Container

I've been kicking the tires on the Command Query Seperation principle/pattern lately. I've been using the CQS-Sample as a starting point. So far, the approach to breaking things down into Commands and Queries is pretty slick and much easier to unit test. The interfaces are used for dependency injection with an IoC container like SimpleIoC (which comes with MVVMLight). If you have done any work with IoC containers, you'll know that you need to register your types with the container either explicitly or through some kind of convention. With a few classes it's easy to just bang out the few lines of code you need to do it. In this case, the number of commands and queries is growing and having to explicitly register each one is becoming monotonous. So how to I register my queries and commands without having to write any code to explicitly register my types?


  1. We are working with MVVMLight and SimpleIoC.
  2. For any query or command processor interface there is exactly 1 implementation of it.
  3. All queries are marked with an IQuery interface.
  4. All commands are marked with an ICommand interface (not to be confused with the System.Windows.Input.ICommand).
  5. All command processors implement ICommandProcessor<TCommand> where TCommand is a class that inherits from ICommand.

Step 1: Get an instance of MethodInfo for SimpleIoC's Register<TInterface, TClass>() method.

Normally, getting the MethodInfo for a method you'd like to invoke is more straight forward. This method has 8 overloads so some LINQ was needed to get the correct one.

var registerMethodInfo = SimpleIoc.Default.GetType().GetMethods()
.Where(m => m.Name == "Register")
.Select(m => new
Method = m,
Params = m.GetParameters(),
Args = m.GetGenericArguments()
.Where(x => x.Params.Length == 0)
.Where(x => x.Args.Length == 2)
.Select(x => x.Method)

Step 2: Get a list of all types in the current AppDomain.

This step is pretty straightforward. Notice the .ToList() call at the end of method chain. This is to make sure that when we use types in the following steps, we won't be enumerating the IEnumerable of types more than once.

var types = AppDomain.CurrentDomain.GetAssemblies().SelectMany(a => a.GetTypes()).ToList();

Step 3: Get all query interfaces that inherit from IQuery.

var queryInterfaces = from t in types
where t != typeof (IQuery)
where t.IsInterface
where typeof (IQuery).IsAssignableFrom(t)
select t;

Step 4: Create a query implementation class to query interface mapping

This step creates the query interface to query type mapping. The result is projected into an anonymous type that will be easy to use in the next step.

var queryMappings = from queryInterface in queryInterfaces
from t in types
where t.GetInterface(queryInterface.Name) == queryInterface
select new {queryInterface, Query = t};

Step 5: Register the query types

This is the last bit of reflection needed to register the queries. This code iterates of the query mappings from the previous step, gets a generic MethodInfo using the interface and implementation, and then invokes it on the current SimpleIoC instance.

foreach (var queryMapping in queryMappings)
var genericRegisterMethodInfo = registerMethodInfo.MakeGenericMethod(queryMapping.queryInterface, queryMapping.Query);
genericRegisterMethodInfo.Invoke(SimpleIoc.Default, null);

Step 6: Get a list of classes that inherit from ICommand.

var commands = from t in types
where t != typeof (ICommand)
where typeof (ICommand).IsAssignableFrom(t)
select t;

Step 7: Make the ICommandProcessor<T> interfaces.

This is an interesting step in the process. The command processors do not have a common non-generic interface, so we'll have to make the generic type of ICommandProcessor<TCommand>.


var commandProcessorInterfaces = from command in commands
select new {CommandProcessorInterface = typeof (ICommandProcessor<>).MakeGenericType(command)};

Step 8: Map ICommandProcessor<T> interfaces to ICommandProcessor<T> implementations

Now we'll create the mapping between the ICommandProcessor<TCommand>s and their implementations.

var commandProcessorMappings = from commandProcessorInterface in commandProcessorInterfaces
from t in types
where t.GetInterface(commandProcessorInterface.CommandProcessorInterface.Name) == commandProcessorInterface.CommandProcessorInterface
select new {commandProcessorInterface.CommandProcessorInterface, CommandProcessor = t};

Step 9: Register the command processor types

Same thing as step 5. Just iterating over the command mappings to make the generic MethodInfos and then invoking them on the current SimpleIoC instance.

foreach (var commandProcessorMapping in commandProcessorMappings)
var genericRegisterMethodInfo = registerMethodInfo.MakeGenericMethod(commandProcessorMapping.CommandProcessorInterface, commandProcessorMapping.CommandProcessor);
genericRegisterMethodInfo.Invoke(SimpleIoc.Default, null);

And that's how I register all my command processors and queries through reflection. LINQ and Reflection FTW!

Are there better approaches? Sure. Are there better IoC containers out there? You betcha. But, this approach is Good Enough™ for now.

Category: C#, LINQ | Comments Off on Registering Types With the SimpleIoC Container
July 27

Simplifying Switches Using Dictionaries

Have you ever had to write a long series of if/then statements or a giant switch statement that extends for a page or two of your code? Want an easy way to increase the readability of your code, increase it's maintainability index, and decrease it's cyclomatic complexity? Let's see an example problem and then a possible solution.

Let's start off by considering the following array of anonymous types:

var items = new[]
    new {Operation = Operation.Add, Value1 = 1, Value2 = 2},
    new {Operation = Operation.Subtract, Value1 = 4, Value2 = 3},
    new {Operation = Operation.Multiply, Value1 = 5, Value2 = 6},
    new {Operation = Operation.Divide, Value1 = 8, Value2 = 4},
    new {Operation = Operation.Add, Value1 = 9, Value2 = 10},
    new {Operation = Operation.Subtract, Value1 = 12, Value2 = 11},
    new {Operation = Operation.Multiply, Value1 = 13, Value2 = 14},
    new {Operation = Operation.Divide, Value1 = 16, Value2 = 4},
    new {Operation = Operation.Add, Value1 = 17, Value2 = 18},
    new {Operation = Operation.Subtract, Value1 = 6, Value2 = 3},
    new {Operation = Operation.Multiply, Value1 = 8, Value2 = 8},
    new {Operation = Operation.Divide, Value1 = 10, Value2 = 2}

I need to iterate over this array and execute the given Operation on Value1 and Value2 properties to produce a list of results A brute force method of doing this is as follows:

var results = new List<int>();
foreach (var item in items)
    switch (item.Operation)
        case Operation.Add:
            results.Add(item.Value1 + item.Value2);
        case Operation.Subtract:
            results.Add(item.Value1 - item.Value2);
        case Operation.Multiply:
        case Operation.Divide:
            throw new ArgumentOutOfRangeException();

The switch statement is pretty straightforward and simple to implement in this example. Visual Studio 2013 Code Analysis is giving the code a maintainability index of 54 and a cyclomatic complexity of 6. What if I needed more lines of code to handle each operation? This could turn into a mess to test, debug, and maintain.

A possible solution to this problem is to replace your switch with a dictionary. I realize that seems odd to replace a control statement with a data structure, but refactoring to this approach will simplify your code. In our example, each item in the array has an Operation to be performed on the Value1 and Value2 properties. I can setup my dictionary with the key value being the Operation enumeration, and the value being the Action, Func, or method group that performs the operation.

var operationMethods = new Dictionary<Operation, Func<int, int, int>>
    {Operation.Add, Add},
    {Operation.Subtract, Subtract},
    {Operation.Multiply, Multiply},
    {Operation.Divide, Divide}

In the example above, I'm using the following methods:

public int Add(int left, int right)
    return left + right;
public int Subtract(int left, int right)
    return left - right;
public int Multiply(int left, int right)
    return left*right;
public int Divide(int left, int right)
    return left/right;

With the dictionary approach, our code to iterate over the items and execute the individual operations looks like this:

var results = new List<int>();
foreach (var item in items)
    results.Add(operationMethods[item.Operation].Invoke(item.Value1, item.Value2));

VS2013 gives the refactored code a maintainability index of 63 and a cyclomatic complexity of 2. Our code is still doing the same thing as the switch was, but we have broken the code down to simpler pieces that are more readable and more easily to wrap unit tests around.

I find this to be a good approach to take when the "cases" of our switch statement are known up front (such as using an enumeration). If it is possible that you will not have all the cases or keys in the dictionary, you can still use this approach but you will want to handle things more gracefully with the Dictionary's TryGetValue method like so:

Func<int, int, int> operation;
if (operationMethods.TryGetValue(item.Operation, out operation))
    results.Add(operation(item.Value1, item.Value2));
// TODO: Handle case of the missing case/key

To tie it all together, here is a Gist with the code I discussed in this post.

I hope this helps. If you have any questions or comments, please use the comments form below. Thanks.

Category: C# | Comments Off on Simplifying Switches Using Dictionaries