views:

617

answers:

9

After reading the nice answers in this question, I watched the screencasts by Justin Etheredge. It all seems very nice, with a minimum of setup you get DI right from your code.

Now the question that creeps up to me is: why would you want to use a DI framework that doesn't use configuration files? Isn't that the whole point of using a DI infrastructure so that you can alter the behaviour (the "strategy", so to speak) after building/releasing/whatever the code?

Can anyone give me a good use case that validates using a non-configured DI like Ninject?

+6  A: 

I don't think you want a DI-framework without configuration. I think you want a DI-framework with the configuration you need.

I'll take spring as an example. Back in the "old days" we used to put everything in XML files to make everything configurable.

When switching to fully annotated regime you basically define which component roles yor application contains. So a given service may for instance have one implementation which is for "regular runtime" where there is another implementation that belongs in the "Stubbed" version of the application. Furthermore, when wiring for integration tests you may be using a third implementation.

When looking at the problem this way you quickly realize that most applications only contain a very limited set of component roles in the runtime - these are the things that actually cause different versions of a component to be used. And usually a given implementation of a component is always bound to this role; it is really the reason-of-existence of that implementation.

So if you let the "configuration" simply specify which component roles you require, you can get away without much more configuration at all. Of course, there's always going to be exceptions, but then you just handle the exceptions instead.

krosenvold
but what about no configuration at all (as in google guice) - how do you specify the "component roles"?
JohnIdol
Last time I looked at guice it lacked the "convention over configuration" aspect that you can get by mixing annotations, xml and roles, which is also the reason I'm not using spring javaconfig. I really prefer the mixed paradigm. Replacing xml with code that does the same thing does not cut it for me, maybe it's just me being close minded, but I cannot see how code-based configuration would add value for me. But I don't know if you can achieve a convention based setup in guice.
krosenvold
A: 

If you want to change the behavior after a release build, then you will need a DI framework that supports external configurations, yes.

But I can think of other scenarios in which this configuration isn't necessary: for example control the injection of the components in your business logic. Or use a DI framework to make unit testing easier.

Gerrie Schenck
+1  A: 

you don't even need to use a DI framework to apply the dependency injection pattern. you can simply make use of static factory methods for creating your objects, if you don't need configurability apart from recompiling code.

so it all depends on how configurable you want your application to be. if you want it to be configurable/pluggable without code recompilation, you'll want something you can configure via text or xml files.

cruizer
A: 

You should read about PRISM in .NET (it's best practices to do composite applications in .NET). In these best practices each module "Expose" their implementation type inside a shared container. This way each module has clear responsabilities over "who provide the implementation for this interface". I think it will be clear enough when you will understand how PRISM work.

Nicolas Dorier
Cool, I'll look into that.
Dave Van den Eynde
+3  A: 

With dependency injection unit tests become very simple to set up, because you can inject mocks instead of real objects in your object under test. You don't need configuration for that, just create and injects the mocks in the unit test code.

starblue
Not only unit tests - this is a great way to deploy test/dev version of application with mock components for parts you don't want to test (or show to clients).
Domchi
Right, but why would I need Ninject for that?
Dave Van den Eynde
+1  A: 

I'll second the use of DI for testing. I only really consider using DI at the moment for testing, as our application doesn't require any configuration-based flexibility - it's also far too large to consider at the moment.

DI tends to lead to cleaner, more separated design - and that gives advantages all round.

Duncan
A: 

When you use inversion of control you are helping to make your class do as little as possible. Let's say you have some windows service that waits for files and then performs a series of processes on the file. One of the processes is to convert it to ZIP it then Email it.

public class ZipProcessor : IFileProcessor
{
  IZipService ZipService;
  IEmailService EmailService;

  public void Process(string fileName)
  {
    ZipService.Zip(fileName, Path.ChangeFileExtension(fileName, ".zip"));
    EmailService.SendEmailTo(................);
  }
}

Why would this class need to actually do the zipping and the emailing when you could have dedicated classes to do this for you? Obviously you wouldn't, but that's only a lead up to my point :-)

In addition to not implementing the Zip and email why should the class know which class implements the service? If you pass interfaces to the constructor of this processor then it never needs to create an instance of a specific class, it is given everything it needs to do the job.

Using a D.I.C. you can configure which classes implement certain interfaces and then just get it to create an instance for you, it will inject the dependencies into the class.

var processor = Container.Resolve<ZipProcessor>();

So now not only have you cleanly separated the class's functionality from shared functionality, but you have also prevented the consumer/provider from having any explicit knowledge of each other. This makes reading code easier to understand because there are less factors to consider at the same time.

Finally, when unit testing you can pass in mocked dependencies. When you test your ZipProcessor your mocked services will merely assert that the class attempted to send an email rather than it really trying to send one.

//Mock the ZIP
var mockZipService = MockRepository.GenerateMock<IZipService>();
mockZipService.Expect(x => x.Zip("Hello.xml", "Hello.zip"));

//Mock the email send
var mockEmailService = MockRepository.GenerateMock<IEmailService>();
mockEmailService.Expect(x => x.SendEmailTo(.................);

//Test the processor
var testSubject = new ZipProcessor(mockZipService, mockEmailService);
testSubject.Process("Hello.xml");

//Assert it used the services in the correct way
mockZipService.VerifyAlLExpectations();
mockEmailService.VerifyAllExceptions();

So in short. You would want to do it to 01: Prevent consumers from knowing explicitly which provider implements the services it needs, which means there's less to understand at once when you read code. 02: Make unit testing easier.

Pete

Peter Morris
It's a cool answer and all, but not exactly an answer to my question. I'm fairly aware of what IoC is and what a DI framework does; I just fail to see the reason why do the config itself in code as well.
Dave Van den Eynde
+2  A: 

I'm on a path with krosenvold, here, only with less text: Within most applications, you have a exactly one implementation per required "service". We simply don't write applications where each object needs 10 or more implementations of each service. So it would make sense to have a simple way say "this is the default implementation, 99% of all objects using this service will be happy with it".

In tests, you usually use a specific mockup, so no need for any config there either (since you do the wiring manually).

This is what convention-over-configuration is all about. Most of the time, the configuration is simply a dump repeating of something that the DI framework should know already :)

In my apps, I use the class object as the key to look up implementations and the "key" happens to be the default implementation. If my DI framework can't find an override in the config, it will just try to instantiate the key. With over 1000 "services", I need four overrides. That would be a lot of useless XML to write.

Aaron Digulla
+2  A: 

I received this comment on my blog, from Nate Kohari:

Glad you're considering using Ninject! Ninject takes the stance that the configuration of your DI framework is actually part of your application, and shouldn't be publicly configurable. If you want certain bindings to be configurable, you can easily make your Ninject modules read your app.config. Having your bindings in code saves you from the verbosity of XML, and gives you type-safety, refactorability, and intellisense.

Dave Van den Eynde