I've been learning IoC, Dependency Injection etc. and enjoying the process. The benefits of decoupling and programming to interfaces are, to me, a no-brainer.
However, I really don't like binding myself to a specific framework like Unity or Autofac or Windsor - because I'm still learning and haven't yet decided which is best for my purposes.
So, how can I wrap around something like Unity so I could easily swap in Windsor at a later date? (or whatever). And don't you dare say use another one to inject the first one ;)
Thanks!
R.
P.s. I tagged Unity as that's my current personal preference (I just lurve Entlib).
The concept is actually really simple: Giving a component all the things it needs to do its job. In general, it means decoupling components by providing their dependencies from the outside, instead of creating them directly, which would create adhesion.
Dependency Injection is the method of providing the dependencies and Inversion of Control is the end result of Dependency Injection. IoC is a design principle where the control flow of the program is inverted.
The IoC container is a framework used to manage automatic dependency injection throughout the application, so that we as programmers do not need to put more time and effort into it. There are various IoC Containers for .
You can certainly try making an abstraction from the container by declaring an IContainer
with say Resolve
and Register
. I did that a couple of times. Then you would go ahead and implement a Container : IContainer and encapsulate an actual IoC container with your abstraction. I tried that with Unity and Castle Windsor.
But hey, soon I realised that this was really an over-engineering. I then understood that I tried to abstract from abstraction, yet to build another abstraction. This could be fine to learn the concept, but it was a real pain in the neck in a real project. I would highly recommend against an abstraction from IoC container. If you correctly use DI principle it will be fairly easy to change your container anyways.
The code looks overcomplicated, like
//I did this mess with Service Locator
var t = ContainerService.Instance.Resolve<IMyType>();
//others could go further with same Service Locator
var t = IoCFactory.Instance.CurrentContainer.Resolve<IMyType>();
//better way, use --> IoC and DI <--
//when a program starts, or a new instance of the context created
var t = Container.Resolve<IMyType>() //this lives at the bottom of the stack
//and then you just pass IMyType to the constructor of other types
//you don't need to call Resolve again in the logical cycle
See this post by Ayende.
Yes, they abstracted the Inversion of Control Container. I think that if you need to do that, it is pretty clear that you don’t really get what IoC is all about.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With