Preventing .NET Core Nested Project References
Asked Answered
Q

2

11

Given the situation that I have a .NET Core 2.0 Application I also have a Web assembly, a Business assembly, and a DataAccess assembly.

I don't want the Web assembly to directly reference my DataAccess assembly (Which has my Entity Framework stuff inside of it). This to protect the Web assembly from taking shortcuts and talking to the DbContext directly.

So I have my Web referencing Business and Business referencing DataAccess.

Now for some odd reason, in the Controllers in my Web project, I can still directly access the DbContext, because this is marked as public in my DataAccess project, and apparently it is given to the Web project by some form of nested references.

I suppose a similar topic is this one: https://github.com/aspnet/Mvc/issues/6635 But I couldn't find much on the subject here on Stack Overflow.

Is there any elegant way to prevent these nested dependencies to be accessed by the top level project?

Quartus answered 14/9, 2017 at 10:13 Comment(0)
H
7

In order to prevent your DataAccess layer to be visible from a web layer, you should put PrivateAssets element inside a .csproj file of your business layer. Like in a code below.

<ItemGroup>
 <ProjectReference Include="..\GiveAway.Data\GiveAway.Data.csproj">
   <PrivateAssets>all</PrivateAssets>
 </ProjectReference>
</ItemGroup> 

Here you can read more information about PrivateAssets element: https://learn.microsoft.com/en-us/dotnet/core/tools/csproj

Huertas answered 3/1, 2020 at 20:7 Comment(0)
K
-5

This is why you use interfaces, not concrete objects for injection. You shouldn't be leaking references to DBContext outside of your DataAccess assembly. This means you have too much coupling to the underlying database in the higher layers.

Kaylenekayley answered 14/9, 2017 at 13:24 Comment(1)
Rob, this is not what the question is about. I AM doing everything over abstraction. But in order to use Entity Framework Code First, I will need a public DbContext. I moved all of the DataAccess related items in my DataAccess assembly... I CAN however access my DbContext directly from the Web project, because .NET Core allows me to directly access all dependencies from its own project dependencies recursively.Quartus

© 2022 - 2024 — McMap. All rights reserved.