My JavaScript is Showing in my C#

I was working with our in-house dependency injection framework today and I found myself having to:

  1. Temporarily swap out a dependency in an object into a temp variable so I could inject a alternative implementation in for processing, then replace the original value later.
  2. Let another object access the dependencies another object is keeping track of and use a dependency.

So, I wrote a function:

public T GetDependency<T>()
{
   return (T)_dependencies.Where(d => d is T).FirstOrDefault();
}

So it just crawls an internal list and when it finds the match for the interface being sought, it returns the implementing object.  Great!  Er, until I needed to work with three dependancies.

I don’t know if this code is going to live, but I wrote another function to solve my problem:

public void GetDependencies(object obj)
{
   var fields = obj.GetType().GetFields(Instance | NonPublic)
          .ToDictionary(f => f.FieldType, f => f);

   foreach(var dep in _dependencies)
   {
      Type remove = null;
      foreach(var key in fields)
      {
         if(key.IsAssignableFrom(dep))
         {
            fields[key].SetValue(obj, dep);
            remove = key;
         }
      }

      if(remove != null)
         fields.Remove(remove);
   }
}

Then I did this:

var config = new 
{
   GrabFirstThing = (IFirstThing)null,
   GrabSecondThing = (ISecondThing)null,
   GrabThirdThing = (IThirdThing)null
};

Registry.GetDependencies(config);

And thought, “My JavaScript is showing.”  But!  Instead of having no idea what any of the properties of the anonymous object are, as would be the case if I used dynamic (which I can’t because of a mobile target),  they’re type safe and right there.  Now, is the above better than the following from a usability standpoint?

var thingOne = Registry.GetDependency<IFirstThing>();
var thingTwo = Registry.GetDependency<ISecondThing>();
var thingThree = Registry.GetDependency<IThirdThing>();

That I don’t know.  From a performance standpoint, there are a number of strikes against it.  Creating the dictionary, using reflection to set values on an anonymous object.  So I’m thinking now I’ll probably make the change to the three separate calls.

Wouldn’t Dr. Ian Malcom be proud?  And I say this with apologies to Jurassic Park, I got preoccupied with whether or not I could AND I paused to think if I should!