1

I want to introduce DI to an existing big code base that has many layers of inheritance and abstraction (and references going every which way!). At one of the lowest levels I want to use DI to control the life style of a particular object to be singleton (the current implementaion uses ThreadStatic and has issues). Do I need to inject this from the top all the way down and have all the objects registered in the container (which is a lot of work) or is there a way I can do this quick and dirty style (for now;)? I'm using C# and Castle Windsor.

Steven
  • 166,672
  • 24
  • 332
  • 435
user195166
  • 417
  • 5
  • 16
  • I would not start introducing new patterns as long as there are such obvious quality problems with the existing code base. DI wont solve the problem of spaghetti code, reference hell or misunderstood OO practices. DI is just another tool, not a silver bullet. – Sebastian Weber Apr 19 '12 at 08:11
  • I don't agree with @SebastianWeber. DI has the tendency to show design problems with the code base. Most of the time you find it hard to do proper DI, the problem is caused by violating SOLID (or other) principles. So introducing DI can be very good, but can of course be very challenging, since you are working on a legacy (and probably spagetti) code base. – Steven Apr 19 '12 at 12:55
  • I just finished some code on a project with an architecture that doesn't use dependency injection, but uses the Singleton design pattern all over the place (the horror). Although it was impossible for me to use a DI container, I still was able to design my classes around the DI principle. I had to cheat in the main type by introducing a default constructor that called an other constructor with the dependencies it needed (the Poor Man's DI anti-pattern). Although sub optimal, it allowed me to write new code that was clean and testable and I did this without changing anything else to the system. – Steven Apr 19 '12 at 15:36

1 Answers1

0

You could go for a service locator pattern that provides the container. It is considered a bit of a bad practice by many Is it bad to use servicelocation instead of constructor injection to avoid writing loads of factory classes but one could argue its better then nothing if the option for you is to have hard dependencies and buggy code. There are some situation that it is not considered that bad http://codeofrob.com/entries/service-location-is-not-always-evil.html

I would however read up a bit on the subject if I were you and see how it fits you needs and your application. DI/IoC debates tend to get a bit religious sometimes imho.

Community
  • 1
  • 1
Jon
  • 561
  • 4
  • 14