Search code examples
vbadependency-injectioninversion-of-controlioc-containerrubberduck

IoC container for VBA


Had a nice read about DI here in VBA:

https://rubberduckvba.wordpress.com/2016/07/05/oop-vba-pt-2-factories-and-cheap-hotels/

So now the next step would be use an IoC container in VBA. But I am wondering if that's even possible! I'm new to VBA and I cant figure out a few things:

  1. If done in VBA, VBA has no namespaces or Type equivalent from C#. So how would my lookup table store a unique key for a type?
  2. I thought about writing a com dll in C# and implement an IoC there but I cant figure out how to pass on a Interface type to the com interface. I cant even instantiate an interface to pass it as an object to com.

Am I reduced to just using strings and implement namespaces in VBA using modules?

PS: I did not find any exisiting implementation of IoC container for vba, so if there's any, I'm all ears!


Solution

  • That's the literal Holy Grail we've been chasing all along: the ability to instantiate a VBA class in-process, from C# code. The minute we figure out how to do this, an IoC container for VBA code becomes a definite possibility, and would absolutely ship with Rubberduck along with a full-blown mocking framework.

    A VBA solution is probably not possible, since as @this alluded to, Newing up a class instance dynamically without a type system and without reflection, ...is pure black magic wizardry.

    Setting aside the technical issues, one has to wonder: would an IoC container make such a huge difference?

    The truth is, it wouldn't. Dependency Injection doesn't need an IoC container, "Poor Man's DI" works perfectly fine and, I may add, is even preferable.

    I submit that if you've reached the point where an IoC container makes sense for your VBA project and you understand everything about DI and SOLID and write your code accordingly... then [not to take anything away from VBA but] my assessment is that you're completely beyond ready to move on from VBA and work with more OOP-capable languages, such as VB.NET or C# - and use everything you've learned about OOP in VBA while discovering a whole new range of possibilities through parameterized constructors, class inheritance, delegates, lambdas, LINQ, and so many other things.