[I am not the post boy for doing DI; I’m on good record for seeming to be against it, but I was reading an article on DI (yes, I read up on a number of things that run counter to my beliefs... I’m a thinker, so I think debate is a good thing and learning about the stuff outside your normal realm is a way to better yourself).]
I don’t think I’ve ever seen anyone talk about this and I did it recently. Basically you create a class like this:
1: public class MyClassWithADependency<T> : SomeBaseClass where T:ISomeInterface,new()
2: {
3: T _dependency;
4: public MyClassWithADependency()
5: {
6: _dependency = new T();
7:
8: // Use _dependency in the rest of your code
9: }
10: }
If you are a TDD guy (or are familiar with unit testing), you have just enabled a whole scenario of things. Mind you have I have no idea how well this works with an IOC library (Ask Jeremy Miller or one of those guys), but the idea really has some merit for me (although I won’t be doing this everywhere).
In my case I am preparing for an expansion on a library I just wrote for work. It has something to do with reading Excel documents with FarPoint Spread and importing the data... what quickly came to light is that there will very quickly be a number of new requirements for our app that use Excel imports (so new data, so parsing mechanisms). BTW, our mechanism uses FarPoint to generate an Excel export file that is used by our users for data entry.
Anyway, I wanted to keep much of my parsing routines, but merge in new data structures. Injection via generics works great. I was even able to derive a new class based on a specific generic like this:
1: public class MyNewClass : MyClassWithADependency<ClassThatImplementsISomeInterface>
2: {
3: public MyNewClass() : base()
4: {
5: }
6: // Rest of your definition goes here
7: }
Testing??
Since I’m not a TDD guy nor do I use Automated Test tools like MbUnit on a heavy basis, I will defer on this one. I will rely on someone like Chad or one of my regular readers to do it for me.
[Of course this example may be totally "whack" in which case tell me, please...]
Print | posted on Thursday, September 18, 2008 11:39 AM