3

Imagine I have four projects in my solution:

  • UI <- startup project
  • Domain
  • Repository
  • Boot

The UI projects has dependencies to the Domain and Boot projects.

The Boot project has dependencies to the Domain and Repository projects for DI container configurations.

If I write this in ASP.NET Core 5, the UI code can access and instantiate Repository classes, even if I didn't have a dependency in the UI project.

In .NET Framework 4.8, this did not happen. This behavior turn an isolation impossible, so Dependency Inversion Principle in this configuration is easily breakable.

There is a way to turn that behavior off in ASP.NET Core 5?

  • 2
    1 this is normal behavior in .NET since you are using "direct references". 2 your code should depend on abstractions not concretions. So instead of referencing concrete classes you should be referencing interfaces and injecting the concrete classes. 3 The only project which needs to references the concrete classes is the Entry Point which I guess is the Boot in your setup??? Your dependencies do not seem Inverted so your design seems to violate Dependency Inversion. Dependency Injection only really makes sense when your layers are correctly designed – Jonathan Alfaro May 17 '21 at 03:06
  • 1
    The whole point of Dependency Injection is to implement Dependency Inversion and avoid "direct references". This creates a loosely coupled model, which then can be instrumented for unit testing for example. – Jonathan Alfaro May 17 '21 at 03:09
  • In summary the Entry Point decides which concrete classes to Inject down into the object graph. And all other classes will depend on interfaces passed down as constructor parameters. Interfaces must live in separate components and NOT with the classes which they represent. This ultimately creates indirection layers to allow you to "decouple" your components. – Jonathan Alfaro May 17 '21 at 03:12
  • Are you getting this... when you "code to an interface, not an implementation" and LAYERING your application with different .csproj's? example MyBusinessLogic.csproj, MyDataLayer.csproj (https://learn.microsoft.com/en-us/dotnet/architecture/modern-web-apps-azure/common-web-application-architectures ) – granadaCoder May 17 '21 at 12:25
  • 1
    Related: https://stackoverflow.com/questions/9501604/ioc-di-why-do-i-have-to-reference-all-layers-assemblies-in-applications-entry – Steven May 17 '21 at 14:31

1 Answers1

2

This is a default behaviour of .NET Core, if you want to change this and don't allow UI to have access to Repository layer indirectly, you can set it like below in .csproj file:

 <ProjectReference Include="..\Boot\Boot.csproj" >
  <ExcludeAssets>all</ExcludeAssets>
</ProjectReference>

To know more about this, take a look at the below link link

osman Rahimi
  • 1,427
  • 1
  • 11
  • 26