Davita
Davita

Reputation: 9114

A question about DI and IoC container

I'm new to DI and IoC pattern. I'm working on a new project and want to maximally loose couple my objects. My classes are split across several projects in solution. So I downloaded NInject and read somewhere that I should create bindings in application startup (Main function or Global.asax). One thing I don't understand, is that in that case, I'll have to reference those assemblies containing the classes to create binding, and this means that the classes is coupled with the object in which I create bindings. Is that right? Does this means that using MEF is a better idea? Anyone can explain how things work with IoC and why it's a good idea to use it? Thanks

Upvotes: 2

Views: 296

Answers (2)

NOtherDev
NOtherDev

Reputation: 9672

In the simplest approach, your binding (container configuration) need to know all the referenced classes and it is sufficient in most cases.

If it isn't in your case, some IoC containers can have multiple bindings/configurations. In StructureMap the binding is called Registry and you can specify to include multiple registries or even scan the libraries in specified directory to dynamically include all the registries. I remember NInject offers the possibility to configure the kernel from more than one place, too.

Using MEF wouldn't be any better here I believe. You'll have to share the common interfaces between projects, too. And MEF is for runtime composability, when you can't compose the system at design time, which is not the case here if I understand correctly.

Upvotes: 0

Adam Terlson
Adam Terlson

Reputation: 12730

Inversion of Control isn't about not having references to assemblies, it's more about creating contracts between your logic and dependent services. It facilitates testability and re-usability by abstracting out the concrete instantiation of your services when they are used.

This allows you, for example, to pass in a different data service that'll save your data into an in-memory table instead of your database meaning that you're not saving data to your database during unit tests. Your function that does the work doesn't care what's passed in because whatever it is, it implements a common interface that you can execute functions against with reasonable assumption that they'll work.

There's a bunch of good resources available to learn more about the IOC/DI pattern. Here's a couple:

Ninject Sample

Wiki Article

And some site called "stack overflow"

Upvotes: 2

Related Questions