Software Development

Paramore Brighter: Ensuring Dependencies are Disposed.

In my previous post, I showed how to set up Paramore Brighter with the built in Dependency Injection provided with .NET Core 2. However, it wasn’t the full story.

The code for this post is on GitHub.

In reality the various classes you might need will have different lifecyles, and along with that there are different needs for cleaning up. Some objects might be singletons and you get the same object back every time, some might be transient where you get a different object back every time, and in some cases you need the same object back for the the duration of the action you are doing, but a different object back at other times.

We’re going to look at the last scenario, objects that have a “scope”. For example, say somewhere you need to access a DbContext from Entity Framework. You probably want the same context for the duration of handling the command, but a separate one next time around. This is especially true if your application can handle multiple commands at the same time (e.g. An ASP.NET Core application) – You don’t want one handler to initiate SaveChanges() on the same context as another is still making changes to the data model.

We also want to make sure that any objects that need to be disposed of at the end of handling a command are properly disposed of, whether it is the handler itself, or an object that was injected into it.

To that end we’re going to make some changes to the code from the previous application.

The BuildServiceProvider() method changes the handlers to being scoped:

private static IServiceProvider BuildServiceProvider()
{
    var serviceCollection = new ServiceCollection();
    serviceCollection.AddScoped<SalutationHandler>();
    return serviceCollection.BuildServiceProvider();
}

The ServiceProviderHandler class that was created in the previous post needs to take into account that after a command is handled, the resources it uses need to be disposed.

public class ServiceProviderHandler : IAmAHandlerFactory
{
    private readonly IServiceProvider _serviceProvider;
    private readonly ConcurrentDictionary<IHandleRequests, IServiceScope> _activeHandlers;
    public ServiceProviderHandler(IServiceProvider serviceProvider)
    {
        _serviceProvider = serviceProvider;
        _activeHandlers = new ConcurrentDictionary<IHandleRequests, IServiceScope>();
    }
    public IHandleRequests Create(Type handlerType)
    {
        IServiceScope scope = _serviceProvider.CreateScope();
        IServiceProvider scopedProvider = scope.ServiceProvider;
        IHandleRequests result = (IHandleRequests)scopedProvider.GetService(handlerType);
        if (_activeHandlers.TryAdd(result, scope))
            return result;

        scope.Dispose();
        throw new InvalidOperationException("The handler could not be tracked properly. It may be declared in the service collection with the wrong lifecyle.");
    }

    public void Release(IHandleRequests handler)
    {
        if (_activeHandlers.TryRemove(handler, out IServiceScope scope))
        {
            scope.Dispose();
        }
    }
}

The changes are that we now keep a dictionary of active command handlers and the scope they are in. When we are asked to Create() a new handler, we:

  • create a new scope,
  • get a services in the context of that scope, and
  • store the handler and scope in the dictionary (keyed on the handler)

If the handler cannot be added to the dictionary, then we Dispose() of the scope (which also disposes the handler if it is disposable) and we throw an exception to say that something went wrong. Generally, the same handler should never end up in the dictionary twice, but it might if it was set up with a Singleton lifecycle and multiple threads are trying to use it. So, we guard against that. In a single threaded application, this code is not likely to be hit even if the handler was defined as a Singleton because it will have been removed from the dictionary at the end of its previous operation.

Once the command has been handled, the Release() method is called which

  • looks up the handler in the dictionary to get the scope, while it
  • removes the handler and scope from the dictionary, and then
  • disposes of everything in that scope.

Just to show that this all works, I made the command handler implement the IDisposable interface and just put in a Console.WriteLine() to show that it was called.

public class SalutationHandler : RequestHandler<SalutationCommand>, IDisposable
{
    public override SalutationCommand Handle(SalutationCommand command)
    {
        Console.WriteLine($"Greetings, {command.Name}.");
        return base.Handle(command);
    }

    public void Dispose()
    {
        Console.WriteLine("I'm being disposed.");
    }
}

The Main() method now creates two commands:

commandProcessor.Send(new SalutationCommand("Christian"));
commandProcessor.Send(new SalutationCommand("Alisdair"));

And the resulting output is:

Greetings, Christian.
I'm being disposed.
Greetings, Alisdair.
I'm being disposed.
Software Development

Paramore Brighter: Using .NET Core’s Dependency Injection

This is the first in a series of posts on Paramore.Brighter. I’m writing this as a series of recipes, with the aim of you picking up a point quickly and getting going with it.

The code for this post is on GitHub, you can find it here: GitHub Basic solution

In .NET Core there is now a Dependency Injection framework built in. Obviously, you can use your own, but for simplicity (and because a lot of people will take what comes in the box) I’m going to show you how to use the dependency injection framework that comes out of the box. It is what ASP.NET Core applications will use by default.

The Command & Handler

If you’ve already read a bit about how Paramore Brighter works, you’ll probably already know how to create commands and command handlers, but we’ll just recap anyway. We’re going to create a simple Hello World scenario.

Our command and handler look like this:

public class SalutationCommand : IRequest
{
    public Guid Id { get; set; }

    public string Name { get; }

    public SalutationCommand(string name)
    {
        Id = Guid.NewGuid();
        Name = name;
    }
}

public class SalutationHandler : RequestHandler<SalutationCommand>
{
    public override SalutationCommand Handle(SalutationCommand command)
    {
        Console.WriteLine($"Greetings, {command.Name}.");
        return base.Handle(command);
    }
}

Nothing too complex here. The command is used to pass some information to the handler, in this case a name, we’ll not worry about the Id for the moment, it is required by the IRequest interface, and at this stage can be anything you want. The handler then writes a greeting to the console using the name it was given.

Configuring the command processor

At a most basic level, the command processor needs to know just two things.

  1. How to map commands to their handler
  2. How to build a handler

Everything else it can do can come later, but without those two things it does not work.

The first thing the configuration does it build a registry of commands and their handlers.

private static SubscriberRegistry CreateRegistry()
{
    var registry = new SubscriberRegistry();
    registry.Register<SalutationCommand, SalutationHandler>();
    return registry;
}

The second thing it does is create a class, implementing the IAmAHandlerFactory interface, that will build the handler, and in our case, it uses the IServiceProvider to do that.

public class ServiceProviderHandler : IAmAHandlerFactory
{
    private readonly IServiceProvider _serviceProvider;
    public ServiceProviderHandler(IServiceProvider serviceProvider)
    {
        _serviceProvider = serviceProvider;
    }
    public IHandleRequests Create(Type handlerType)
    {
        return (IHandleRequests)_serviceProvider.GetService(handlerType);
    }

    public void Release(IHandleRequests handler)
    {
    }
}

This is a very simple implementation that just calls the GetService() in the Create() method to get the command handler object from the container. It doesn’t do any clean up, or any validation.

Putting it all together

Finally, a builder object is used to wire all that together and produce a command processor

private static IAmACommandProcessor BuildCommandProcessor(IServiceProvider serviceProvider)
{
    var registry = CreateRegistry(); // 1. Maps commands to Handlers
    var factory = new ServiceProviderHandler(serviceProvider); // 2. Builds handlers

    var builder = CommandProcessorBuilder.With()
        .Handlers(new HandlerConfiguration(
            subscriberRegistry: registry,
            handlerFactory: factory))
        .DefaultPolicy()
        .NoTaskQueues()
        .RequestContextFactory(new InMemoryRequestContextFactory());

    return builder.Build();
}

There are other things this is doing, but for the moment we’re not concerned about them.

And that’s it, the only thing left is the entry point (the Main method) of the application.

static void Main(string[] args)
{
    var serviceProvider = BuildServiceProvider();
    var commandProcessor = BuildCommandProcessor(serviceProvider);

    commandProcessor.Send(new SalutationCommand("Christian"));

    Console.ReadLine();
}

When run, it emits a single line at the console, which reads:

Greetings, Christian
Talk Follow-up

Imposter Syndrome

This is a quick write-up of my near-impromtu grok talk on Imposter Syndrome I did at DDD East Anglia.

Impostor syndrome (also known as impostor phenomenon or fraud syndrome or the impostor experience) is a concept describing individuals who are marked by an inability to internalize their accomplishments and a persistent fear of being exposed as a “fraud”. — Wikipedia.

I wanted to talk about Imposter Syndrome in relation to talking at User Groups or conferences, such as DDD. The common complaint is that “I’m not good enough”.

Way back in the early days of Scottish Developers (2004), one of the organises suggested I do a talk on SQL Injection Attacks as I had been talking about it in the pub after an event and he recognised I was quite knowledgeable about how to prevent it. I protested, but he continued to try and persuade me. Eventually I did do a talk the following year and I got good feedback from it. I thought I was behind the curve and everyone knew more than me, but it turns out that wasn’t the case.

Last year .NET Rocks came to Scotland and one of the interviewees, Chris McDermott, said he felt a little like an imposter after they had interviewed such luminaries as Dan North, folks that had published books. But, having worked with him, I know he really knows his stuff, and he gave an awesome interview.

But don’t just take my experience or others in the developer community with imposter syndrome, some really clever people including Professor Richard Feynman, who won the Nobel Prize for Physics in 1965 for, as a he described it, as a result of piddling about with plates. He also helped develop the atom bomb in the 1940s and worked out why the Callenger Space Shuttle exploded shortly after takeoff in 1986. Yet, in a speech in the mid-1970s he said he felt like a fraud. He said he was just playing and having fun.

Meryle Streep once said in an interview: “You think, “Why would anyone want to see me again in a movie? And I don’t know how to act anyway, so why am I doing this?”

Daniel Radcliffe said: I think the most creative people veer between ambition and anxiety, self-doubt and confidence. I definitely can relate to that. We all go through that: “Am I doing the right thing?” “Is this what I’m meant to be doing?”

So if these talented people get impostor syndrome and they’re really talented, maybe you are too. Maybe you could do this, and be really good at it.

So I encourage you to try, ask to speak at a local user group. Maybe just start with a grok talk or a lightening talk and work up. But you are better than you think you are!

Software Development

Join Null Check with Assignment

2017-07-16-join-null-check-with-assignment

I recently wrote some code and asked ReSharper to add a null check for me, which it did. Then it suggested that I could simplify the null check by joining it to the assignment.

Intrigued, I let it.

The code went from this:

public void SetMessage(string message)
{
    if (message == null) throw new ArgumentNullException(nameof(message));
    Message = message;
}

To this:

public void SetMessage(string message)
{
    Message = message ?? throw new ArgumentNullException(nameof(message));
}

So, I assign message to the property Message unless it is null in which case I throw the exception. This is a new feature in C# 7 called a “throw expression”.

At first glance, I thought it would still assign null to Message before throwing the exception, but that’s not what the code looks like underneath.

I got out my trusty dotPeek to see what it actually compiled to. (Don’t worry, I’m not going to show you IL, just what the C# looks like without the syntactic sugar). The result was this:

public void SetMessage(string message)
{
  string str = message;
  if (str == null)
    throw new ArgumentNullException("message");
  this.Message = str;
}

Excellent, it is still doing the null check in advance. So the semantics of what I wrote have not changed. That’s great. I learned something new today.

But…

ReShaper also suggested it in an overloaded version of that function that takes two parameters. And the result was not semantically equivalent. So, be careful. Here’s what happened there. I started with this:

public void SetMessage(string message, string transitionMessage)
{
    if (message == null) throw new ArgumentNullException(nameof(message));
    if (transitionMessage == null) throw new ArgumentNullException(nameof(transitionMessage));

    Message = message;
    TransitionMessage = transitionMessage;
}

Let ReSharper refactor to this:

public void SetMessage(string message, string transitionMessage)
{
    Message = message ?? throw new ArgumentNullException(nameof(message));
    TransitionMessage = transitionMessage ?? throw new ArgumentNullException(nameof(transitionMessage));
}

And, I’m beginning to get a little apprehensive at this point because I think I see a problem. In fact, when I look at it in dotPeek, I can see exactly what the issue is. Here’s the same code with the syntactic sugar removed:

public void SetMessage(string message, string transitionMessage)
{
  string str1 = message;
  if (str1 == null)
    throw new ArgumentNullException("message");
  this.Message = str1;
  string str2 = transitionMessage;
  if (str2 == null)
    throw new ArgumentNullException("transitionMessage");
  this.TransitionMessage = str2;
}

It does the first null check, then assigns to the Message property. Then it does the second null check… And that’s not what I want at all. This method should be an all or nothing proposition. Either both properties are set, or neither are changed and this isn’t the case any more.

Caveat Programmator, as they say in Latin.

Software Development

Aggregate of columns, not rows

In SQL Server it is very easy to aggregate a value across many rows. You simply just write something like this:

SELECT MAX(SomeColumn)
FROM SomeTable

This will return one row with the aggregate value (in this case MAXimum) of the column.

However, what if you want to do this across columns. What if you have a table with two or more columns you want to aggregate for each row?

You can do this with a tedious case statement that just gets more and more cumbersome for each additional column you have, especially if any of the columns are nullable. Or, you can create a subquery with a table in it and you aggregate the table in the subquery exposing the final value to your main query already aggregated.

Here’s an example:

SELECT Id, 
       (SELECT MAX(num) FROM (VALUES(st.ANumber), (st.AnotherNumber)) AS AllNumbers(num)) AS MaxNumber
FROM SomeTable st

The second line contains the subquery which is then exposed as a column in the final result set.

The subquery effectively pivots the columns into rows, then aggregates the rows. Just be careful with where you put the brackets so that it interprets them as separate rows rather than columns.

This also deals with NULL values quite effectively too, since the aggregate function will ignore any null value it finds.