2

I have an ASP.NET web project referencing a service layer class library. I am using dependency injection which I setup in the web layer. I want to take advantage of dependency injection in both projects. But I do not want the web layer to be able to inject certain implementations from the service layer.

An example, I'm using entity framework in the service layer to inject entity repositories into service classes, though I do not want the web layer to have access to inject these entity repositories.

Is there a way to achieve this?

I am playing around with Ninject and AutoFac, so examples using either of these would be fine.

Andrew
  • 5,525
  • 5
  • 36
  • 40
  • can you show a specific code example? It's hard to tell what problem you are coming across – Caleb Mar 12 '14 at 23:35
  • Why do you want to achieve this? This might give us a better understanding of what the goal is. I've written many projects using di but never needed to do this. – matt_lethargic Mar 13 '14 at 00:38
  • As per my example, say you have a service layer containing service classes and entities (using EF). Now, I want to inject those entities into services. Though in the web layer I am also able to inject these entities. I want the web layer to go through the appropriate service in order to access entities, not have direct access to entities. Perhaps getting a little more specific, if I change my entity classes and interface from public to internal, this will hide them from the web layer, but can I still use dependency injection, as the container is setup in the web layer? – Andrew Mar 13 '14 at 03:11
  • Doesn't make any sense. If they are internal/private you won't able to inject them, nor setup the container inside the web layer since the setup code won't see the classes. – cvbarros Mar 13 '14 at 11:37
  • Related: http://stackoverflow.com/q/9501604/126014 – Mark Seemann Mar 13 '14 at 14:08

1 Answers1

1

You can explicitly use two Composition Roots for that end. Setup the container as you normally would for you Web application.

Then in your service layer, use some code to perform initialization of the container only once (a bootstrapper). Within each entry point in your service layer you then ask for internal objects to the layer using your container (service locator). In this fashion, external projects won't be able to interfere with your service layer bindings.

Another way (with Ninject) is to use modules, although it won't shield the outer project from replacing bindings. But you can at least achieve separation of concerns and declare the bindings near where they are used. Things that are injected into Web layer are declared in WebModule, service layer Service Module and so on.

cvbarros
  • 1,684
  • 1
  • 12
  • 19