Posts
1147
Comments
890
Trackbacks
1
December 2014 Blog Posts
A way to handle open generics using Simple Injector

In case I need to do this again, this works, however ‘ugly’ it might be.  This isn’t supposed to be a best practice or anything (there are no such things as best practices, and even if there were some, I wouldn’t know them, since I’m not a very good developer).

Some code:

public interface ICommand {}

public interface ICommand<TReturnValue> : ICommand
    {
        TReturnValue ReturnValue { get; set; }
    }

public class Command : ICommand  {}

public class Command<TReturnValue> : ICommand<TReturnValue>
    {
        public TReturnValue ReturnValue { get; set; }
    }

There’s more to commands than this, but this will suffice.  And yes, I know that some people don’t like commands that return values.  That’s nice.

So now, I want to be able to handle them.

public interface Handles<T, TReturnValue> where T : ICommand<TReturnValue>
    {
        TReturnValue Handle(T command);
    }

public interface Handles<T> where T : ICommand
    {
        void Handle(T command);
    }

Simple enough.

Now, I need to be able to publish commands.

public interface ICommandBaseBus
    {
        void Publish<TCommand>(TCommand command) where TCommand : Command;
        TReturnValue Publish<TCommand, TReturnValue>(TCommand command) where TCommand : Command<TReturnValue>;
    }

Still quite simple.

Now, here’s where Simple Injector comes in.  I don’t want to ‘hand’ register these things together, I want to just scan that sort of stuff.

I tried Autofac, Ninject, StructureMap, and Simple Injector.  I am showing how to do it with Simple Injector because, well, it’s the first one I got to work.  There’s no other reason than that.

Let’s implement the bus.

public class CommandBaseBus : ICommandBaseBus
{
    private Container _container; 

    public CommandBaseBus()
    {
        _container = new Container();

        _container.RegisterManyForOpenGeneric(typeof(Handles<>),
(serviceType, implTypes) => _container.RegisterAll(serviceType, implTypes),
typeof(Handles<>).Assembly);

        _container.RegisterManyForOpenGeneric(typeof(Handles<,>),
(serviceType, implTypes) => _container.RegisterAll(serviceType, implTypes),
typeof(Handles<,>).Assembly);

        _container.Verify();
    }
}

A few things of note:

You need to specify using SimpleInjector.Extensions namespace to get the RegisterMany…. method, which does the fun automagic stuff of connecting your handlers with the relevant commands.

It can get more complicated than this, which I will show in a subsequent post.

I like the Verify() call.  A lot.  I have a tendency to forget to do things, and so when I was ‘hand’ registering stuff, I’d forget to check if everything was wired up correctly, and so get a bunch of run-time barfdom.   If you have the container manage everything, you get that ‘fail fast’ thing immediately when you fire up the bus.

Your calling code might look like this:

static void Main()
        {
            var cmdBus = new CommandBaseBus();

            var myCommand = new MyCommand();
            var myCommandWithReturnValue = new MyCommandWithReturnValue();

            cmdBus.Publish(myCommand);
            var rv = cmdBus.Publish<MyCommandWithReturnValue, bool>(myCommandWithReturnValue);
        }

MyCommandWithReturnValue implements Command<bool> here.

And when you publish, it might do something like this:

public void Publish<TCommand>(TCommand command) where TCommand : Command
        {
            var regs = _container.GetAllInstances<Handles<TCommand>>();

            foreach(var r in regs)
            {
                r.Handle(command);
            }

            //if (!(command is IVariableResult))
               // _eventBus.Process(command);
        }

and

public TReturnValue Publish<TCommand, TReturnValue>(TCommand command) where TCommand : Command<TReturnValue>
        {
            var regs = _container.GetAllInstances<Handles<TCommand, TReturnValue>>().ToList();

            Handles<TCommand, TReturnValue> r = regs[0];

            TReturnValue trv = r.Handle(command);

            //if(!(command is IVariableResult))
            //    _eventBus.Process<TCommand, TReturnValue>(command);

            return trv;
        }

Ignore the commented out stuff about event bus processing and IVariableResult, I’ll get to that some other time.  Maybe.

And yes, I know that normally you would only have one handler for a command, and yes, I know that my variable names suck.

This takes care of, well, the stuff I care gets taken care of at the moment.

posted @ Tuesday, December 30, 2014 9:12 PM | Feedback (0)
Does your website automatically play videos when you visit and not allow you to turn them off?

Then you suck.

You doubly suck if you allow visitors to turn auto-play off but then ‘forget’ this.

posted @ Monday, December 29, 2014 11:17 AM | Feedback (0)
Repost: Is Unhedged Call Options a Better Metaphor for Bad Code?

When I first started reading and talking to Chris Matts (namedropper?  you’re soaking in it), I had difficulty understanding what he was talking about.  Real options?  Huh?

It’s gotten a little better, and so this makes more sense to me now than it would have.

Writing good code involves so much more than developers (this is why I dislike the Software Craftsmanship movement so much….the idea that ‘well-crafted’ code is inherently good code is simply mistaken), it involves people with many different skillsets, organizations with certain sorts of structures, etc. and so I find these sorts of discussions valuable.

YMMV.  Enjoy.

posted @ Wednesday, December 24, 2014 10:22 AM | Feedback (0)
How do you deal with open generics and either Autofac or StructureMap?

For the longest time, I’ve ‘hard-wired’ my registrations using StructureMap, and I’m trying to do an auto registry type of thing and it just isn’t working, because I’m old and stupid.

I’m trying both Autofac and StructureMap, here’s the Autofac version.

I have an interface:

  public interface Handles<in T> where T : ICommand

I do:

   var assembly = Assembly.GetCallingAssembly();

Then:

  builder.RegisterAssemblyTypes(assembly)
               .AsClosedTypesOf(typeof(Handles<>))
               .AsImplementedInterfaces();

This seems to work (as I can look at my registrations and see stuff), and I can successfully do things like this:

  var cmdHandler = container.Resolve<Handles<MyCommand>>();

Where MyCommand is a class that has a handler.  Resolves just fine.

However, if I try this (because I want to get all of my handlers so that I can do stuff with them in a loop):

  var group = container.Resolve(typeof(Handles<>));

I get an exception, because it says there is nothing registered.

Normally Google (and StackOverflow) is my friend, but nothing I try seems to work.

I’m hoping to have something to update here later, because I know I’ll need it again.

posted @ Monday, December 22, 2014 7:26 PM | Feedback (0)
Old Dog + New Tricks = Ugh

Just one of those days…….

Yes, I’m whining, I know that.

Bleh.

posted @ Monday, December 22, 2014 12:52 PM | Feedback (0)
Repost: Speeding up Entity Framework in long iterative loops

I’ve run into this sort of thing before myself, but Rick has all the good details.

Basically, if you don’t need change tracking, then you can easily turn it off and speed things up greatly.

posted @ Sunday, December 21, 2014 6:23 PM | Feedback (1)
The sort of user requirement that can make a software developer weep, random example #74

Scenario: a console app takes a file, loops through every record in the file, and creates an output file.

“The user has requested that you add delete button functionality.”

posted @ Tuesday, December 16, 2014 11:00 AM | Feedback (0)
A marker? Netflix updates Windows Phone App

It isn’t Windows 10, but it’s something.

Netflix has finally updated their Windows Phone app so that it is more like, well, Netflix.  You can access multiple user profiles, auto ‘continue watching’ (which I actually generally find annoying), etc.

Now, if only TuneIn radio didn’t suck so much.

posted @ Tuesday, December 16, 2014 8:45 AM | Feedback (0)
Random Software Developer Job Key Responsibility #1

Pulled from random job listing sent to me:

• Accountable for partnering with key roles (enterprise architects, infrastructure, etc.) to create solutions that are aligned to architecture standards and principles, leverage common solutions and services

posted @ Monday, December 15, 2014 3:42 PM | Feedback (0)
Please don’t save your view models in your database

For various reasons, I was watching this to learn more about the latest version of Raven DB 3.o (basically, I have a big event/command store and I want to process the raw data into multiple different ‘buckets’ and am looking into various options, including SQL and NoSQL options).

Before I get to my main point….

Normally, I wouldn’t pay much attention to mistakes/issues with the presentation itself.  Things happen.  Network connections go out, that sort of thing.

However, if you are trying to give an example that is key to your overall presentation, and it is not the best example in the first place, then you really need to make sure it works.

For instance, one of the ‘big deals’ about NoSQL, at least in some corners, is ease of developer use.  You can just ‘get coding’ and not have to worry about things like creating databases and tables and schemas and all those horrible things that create ‘friction’ and whatnot.  This is, generally speaking, wrong on multiple levels, but okay, let’s go with it for a minute.

If you are going to use as an example how easy it is to add a property to your object model, and having it add default values to existing objects, as a supposed example of how ‘frictionless’ this is (since adding a column to a table with a default value is so freakin’ hard, you know), then you should actually be able to show that in your presentation.  If you can’t get something that basic to work then it really kind of undercuts the whole, ‘it just works’ vibe you are trying to share.

But besides that….

It is given as an example that when designing the UI for a home page, you might have to do a whole bunch of nasty joins to pull back a bunch of information and isn’t it so much easier and better to be able to just save your view model objects in your database instead.

No, no, no, dear Lord, sweet Almighty, no.

The whole ‘Vietnam of Computer Science’, object-relational impedence mismatch thing is largely a load of hooey.  It isn’t difficult to do these sorts of things.  It is absolutely the case that sometimes, dealing with databases and joins and schema changes and (God help us) database administrators can, and this is a technical phrase, suck.  There is no doubt about this.  But, for the most part, if you are having problems with those sorts of things, you are doing it wrong.

The last thing you want is enabling your developers to randomly persist objects in a database, NoSQL or not, without thought, and think you are going to be able to build a reliable, sustainable system.  You really can’t fix these sorts of things with some magical combination of Hadoop and map-reduce.  Crappy NoSQL persistence is still crappy persistence.

So, please, don’t do that sort of thing.

Thank you.

posted @ Friday, December 12, 2014 11:20 PM | Feedback (2)
Who is Sandro Mancuso?

This is a rhetorical question, of course

I wonder if there was a meeting, complete with secret handshakes, to decide who gets to write the bible.

“Where how it is done is as important as having it done.”

Right.

Translation: “helping developers become more difficult and unproductive than they already are.”

YMMV.

posted @ Thursday, December 11, 2014 11:08 AM | Feedback (0)