I was working with our in-house dependency injection framework today and I found myself having to:
- 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.
- 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)
remove = key;
if(remove != null)
Then I did this:
var config = new
GrabFirstThing = (IFirstThing)null,
GrabSecondThing = (ISecondThing)null,
GrabThirdThing = (IThirdThing)null
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!