Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dependency Injection

I am very new to this, so bear with me.

I have a MVC app using Service/Repository/EF4 pattern and I am trying to use Ninject. I have it working on the controllers, they are constructor injected with services, but the services are constructor injected with repositories and I am not sure where to handle this.

I am trying to make it so each layer only knows about the layer below, is that correct? If so, the MVC app only knows of the Service Layer, and the Service Layer only knows about the Repository Layer, etc. So in my Ninject Module where I am creating the bindings, I can not say:

Bind(Of IRepository(Of Category)).To(Of EFRepository(Of Category))

Where do I handle the injection at?

like image 850
Sam Avatar asked Mar 04 '11 07:03

Sam


1 Answers

The comments to your question does indeed provide some useful information.

I usually organize things like this to accomplish what you're talking about - it's only part of it that applies directly to dependency injection:

  • I set up my Visual Studio solution to have one project/assembly per layer in the application. Having it this way, you must set a reference from one layer's project to another to be able to call that layer. So for example, you set up a reference from the MVC app layer to the service layer, but not from the MVC app to the repository layer, to prevent the MVC app from accessing the repository layer directly.
  • Within each layer's project, I put the interfaces and classes that should be used in the project's top namespace, and put the actual implementation of the interfaces and other classes that should be hidden in a sub-namespace, usually called "Impl" or something like that; theses classes are also declared as "internal", which ensures that they can only be used from within the assembly (layer) and not from another layer by mistake.
  • Each project/layer declares one NInject module that binds the public interfaces to the internal implementation classes.
  • At the composition root of your application (see Mark Seeman's link: Where should I do Injection with Ninject 2+ (and how do I arrange my Modules?)), you create a kernel that loads these modules.
  • The actual injection is mostly done with constructor injection, meaning that the classes themself does not really know anything about injection taking place (sometimes you have to use the [Inject] attribute though, if you have ambigous constructors).
like image 95
Liedman Avatar answered Sep 21 '22 02:09

Liedman