How do Ninject Modules benefit me?

The Preface

I was recently on a project where one of the developers decided to use Ninject as the IoC framework. Notice I said framework because it calls INTO your code, whereas a library doesn’t; but I digress.

Anyway, so I added a NinjectModule to the library, added some dependency definitions to it, and committed it to TFS (a whole other problem).  All is well.

Well not so well. I get an email a few minutes later questioning why I’m doing such a thing as adding a NinjectModule.  I thought for a second–I had gone for a walk around the block to rest my eyes, and began emailing back; the response?  Still confusion. It was then and there that I decided that I was wrong about something. I took for granted that “senior engineers” understood why and how Dependency Injection containers worked.  I brushed off my frustration and started typing.  This is what I wrote, and maybe (I’m not really confident about it) this will help some other person.

The Explanation

Ninject (and other almost all DI frameworks) have an IoC container implementation that’s called something…for Ninject it’s the Kernel.  In principle there is a single Kernel (IoC container) at runtime (almost always, but that’s another story).

What a NinjectModule does is act as a registry for dependencies.  The principle behind it is encapsulation of higher order implementations, and for components to depend on abstractions. The assembly/component is saying, “Hey you module/component that want to reference me, don’t worry about how “IAmAContract” is implemented (an interface I’m exposing as public), just ask for it, and I’ll make it happen”. The assembly provides a public module (a NinjectModule), which in effect is saying, “Hey I’ve got stuff you want, so add it to your Kernel (IoC Container) without knowing exactly what’s implementing what you want”.

So at runtime in the component that’s one-to-one with the Process, the IoC container is configured, and in Ninject’s case, we’ll tell it to either scan the assemblies in the bin for NinjectModules, or explicitly add them.  When this happens, the NinjectModule’s bindings (for this type, use this type) get added to the IoC container, i.e. the Kernel.

In practice this lets us make implementations of a public contract, for example an interface in C#, internal to the owner (in this case, some library we’re building) without the consumer ever having to know or have access to the implementation.

StructureMap 3 You don’t need HttpContextScoped()

For the new version of StructureMap (v3), there’s a nuget package StructureMap.MVC4. When you install the package it will add the resolver and the dependency scope for you. Before this package you may have had to call HttpContextScoped() method on your type assignments–not anymore.

The code in the dependency resolver will create a nested scope, which will get disposed of after the ASP.NET MVC (or WebAPI) pipeline is complete.

IContainer child = this.Container.GetNestedContainer();

Helping people solve technical problems

I’m currently listening to the Coaching Architect presentation that Roy Osherove gave last year, and it led me to this the website and his post 3 Reasons to stop solving other people’s problems for them. I’m still chewing on this to be honest. I come from a background where didactic teaching is the choice of style. However, I’m realizing that the majority of people in today’s society don’t actually have the reasoning skills to ingest the information and form a pattern to reason about.

Leadership is definitely the act of coaching and educating people, and growing them to solve their own problems. You also have to be flexible with your approach. There are different personalities. I’m very independent and self-driven, and other people are more passive.

Know The Cost

If someone tells you that you’re code isn’t efficient because you have too many methods, and you’re writing for the .NET framework, know that you’re on the right side. I had this happen to me this week.

“Although there is a small delay for JIT compilation of each method as it is first called, every method called runs pure native code with no interpretive overhead.” –

It’s well documented, and the penalty is so tremendously inconsequential, if you’ve given it thought: stop. We’re talking fractions of a nanosecond, here.

Write readable code where the intent is expressed clearly and simply. Do that first and foremost; let that be our concern if we’re writing code. There are many, many more things to be concerned about when it comes to performance. If you need that level of performance, code in an assembly language.

Getting Started With DDD Surrounded by Legacy

This is a great read from Eric Evans.  The majority of designers deal with legacy the majority of the time, and getting from the DDD source himself has tremendous value in its practical understanding of businesses, development teams, and adopting new development styles.

“Introducing a difficult new set of development principles and techniques is best done incrementally, as in a pilot project, in a way that allows members of the team to gain experience and allows the organization to assess the approach…” — Eric Evans

Tips for Async Libraries in C# and Methods That Lie

Lucian Wischik, a Program Manager on the Microsoft languages team, did a great job on creating async libraries. The main lessons of his talk cover:

  • Libraries shouldn’t lie
  • Use ConfigureAwait(false)
  • Optimize (if necessary)

I really liked his point that library methods shouldn’t lie, and I wanted to focus on that generally as a development practice.  While he’s specifically covering asynchronous programming, I’ve found this to be one of the most common problems reading code.  So often I see methods that just flat out lie.

I think there are the two big categories of lying methods. here they are:

  1. The pathological liars
    The method just flat out lies about what it does. This most often occurs when it’s changed over time and the developer’s never bother refactoring the method either into different methods, or not updating the name (if it’s still has a single responsibility. Most often, no).It’s possible that this happens immediately.  You must think through why you’re doing something. In Lucian’s talk, he makes it clear that you need to have knowledge about threads, TPL, and async to create async methods.For example, say you’ve got a method that says “IsAuthorized”. It takes some arguments that represent a security context. You’d expect it to return a result saying, “Hey, you can’t do that!”, or “Hey, you can!”.  In fact, the method returns false immediately, does a Bus.Send, and somewhere down the line there’s another bit of code off somewhere, tucked away, that handles the result.  If the “IsAuthorized” method is actually doing this, it would be better to name the method “SendRequestForAuthorization”.
  2. Over achievers
    Anytime you see a method that you wrote and it’s handling multiple responsibilities but says (in its name) that it’s doing one thing, then it’s over achieving.DO NOT try and fix this with a conjunction, resulting in a method that says, “Hey, I do this…AND this….AND this…AND.”, you get the picture.

So the next time you’re done writing a method, ask yourself if it’s an honest method.

StructureMap Registry Convention – How To Find Specific Registries

In StructureMap’s default assembly scanner, there’s a LookForRegistries method.  What exactly does this do?  Well, all it does is eventually call Convention<T> using the default registry convention build into StructureMap.  The interface is IRegistrationConvention–easy enough.

Since in my case, I wanted to use a marker interface for the registries that I wanted my container to pull in, I first defined that.

    /// Marker interface for registries that contain security DSL configuration
    public interface ISecurityRegistry

I still like the explicit nature of the LookForRegistries method, so I then created an extension method for the assembly scanner.

internal static class AssemblyScannerExtensions
/// &lt;summary&gt;
/// Looks for registries using the registry convention specified
/// &lt;/summary&gt;
/// &lt;typeparam name=&quot;T&quot;&gt;The type of registration convention&lt;/typeparam&gt;
/// &lt;param name=&quot;scanner&quot;&gt;The scanner&lt;/param&gt;
public static void LookForRegistries&lt;T&gt;(this IAssemblyScanner scanner) where T : IRegistrationConvention, new()

Next, I defined my convention. Now, I did look at the default registry convention, and used some of simple type checks so the convention could easily knockout types that weren’t registries.

    /// Custom registry convention that will only import in registries that are marked with
    internal sealed class SecurityRegistryConvention : IRegistrationConvention
        public void Process(Type type, Registry registry)
            if (IsSecurityRegistry(type))
                registry.Configure(x =&gt; x.ImportRegistry(type));

        private bool IsSecurityRegistry(Type type)
            if (type.Assembly == typeof(Registry).Assembly)
                return false;

            if (!typeof(Registry).IsAssignableFrom(type))
                return false;

            if (!typeof (ISecurityRegistry).IsAssignableFrom(type))
                return false;

            if (type.IsInterface || type.IsAbstract || type.IsGenericType)
                return false;

            return (type.GetConstructor(new Type[0]) != null);


Finally, my container used the convention with the extension method. You don’t want to call LookForRegistries since that will end up using the default registry convention, and you’ll end up getting registries that don’t have the marker interface.

I think it came together nicely.

var container = new Container(c =>
	c.Scan(s =>
return container;

7 Signs You’re Being Manipulated

My wife and I were driving home from a church service a few Sundays ago, and we got on the topic of manipulation. She pointed out how I don’t like to be manipulated. Who does?  What she really meant was, I’ve got my manipulation detector on constantly. Me, I watch out for it; and even if the content is good, I’ll probably flip the off switch on my ears.

Do you hate being had?  If someone is willing to manipulate you, that person is opening up to you about their morality.  If manipulation is a tactic he’s willing to use, what else?  It’s a con game: a confidence game.

The opposite of manipulation is coercion.  Personally, I’d rather be coerced–if I have to pick.  Why?  Because the person is being direct about what they want.  It’s in your face.  Manipulation is  under handed.

This morning I slipped my ear buds on and went for a run.  Hmmm….some Jimmy Cliff.  On the way back to my house, it dawned on me.  Jimmy is singing “Let Your Yeah Be Yeah”.  How you can know spot if someone is trying to manipulate you?  Here’s the play book:

  1. Avoids bad news
    The person changes the subject covertly so as not to talk about a subject. Bad news is anything they think you won’t like to hear: most likely the truth
  2. Puts a positive spin on bad news
    This is subtly different than a person who is optimistic, but pretty close. Optimists, just as pessimists, can be manipulators.  They’re just going to do it differently.
  3. Uses “maybe” instead of yes and no
    Enough said. You can’t get a straight answer from the person.
  4. Wears a plastic smile
    This one is easy to spot.  Have you gotten the smile where the eyes are wide open?  If the persons lips widen but their eyes are stark, it’s plastic.
  5. Gets the majority to agree, the others will fall in line
    This tactic is basically using the herd mentality.  Manipulators don’t like independent thinkers.
  6. Marginalizes dissenting opinion as unintelligent
    This is pretty close to number 5. Here, you’re intelligence is attacked if you don’t go along with the crowd. Right.
  7. Infers consequences (good or bad) of actions and play down freedom of thought
    The manipulator will often never propose a direct consequence to behavior he or she doesn’t like. Notice I said DIRECT.  If you’re walking away fearing something bad is going to happen to you as result of not doing exactly what this person prefers–yep you’re being played.

Using Sinon.JS Mocks in your AngularJS unit tests

Do you want to use Sinon Mocks in your AngularJS unit tests? Here’s how you assign the mock to your service in your setup. The trick is to use the .value method for registering the mock, and using the object property like so:

var mock = sinon.mock({
	method: function () { }

beforeEach(function () {
	module(function ($provide) {
		$provide.value('serviceName', mock.object);

Testing thread safety of singleton implementation

Here’s one way you can prove thread-safety for a implementation of a singleton.

public void current_should_be_thread_safe()

	int caller = 10;

	var resetEvent = new ManualResetEvent(false);
	var results = new IContainer[10];

	for (int i = 0; i &amp;lt; 10; i++)
		ThreadPool.QueueUserWorkItem(state =&gt;; //WaitCallback

			var @return = InternalContainer.Current;

			int index = Interlocked.Decrement(ref caller);
			results[index] = @return;


	while (caller &gt; 0)

	var expected = InternalContainer.Current;

	for (int i = 0; i &amp;lt; 10; i++)
		Assert.True(expected.GetHashCode() == results[i].GetHashCode());