4

I'm working on a pet project to practice my .NET Core. I'm using a Web Application project with built-in Dependency Injection framework like so

public void ConfigureServices(IServiceCollection services)
{
    services.AddScoped<IProductRepository, ProductRepository>();

    < ... other code ... >
}

It forces me to add reference to my Data project which contains the implementation of the ProductRepository to my WebApplication project. This will mean later on that WebApplication project will need to reference every other project and can abuse that - I don't even want Web to know about repositories, everything should be done via services.

My question is - can I avoid referencing every other project in WebApplication using built-in DI?

(I know I can use other DI containers that will allow to fix this).

Camilo Terevinto
  • 31,141
  • 6
  • 88
  • 120
Alex Buyny
  • 3,047
  • 19
  • 25
  • 2
    You can, but only kinda. Unless you're willing to load the libraries manually at runtime, the entry point (your app) will always end up with a dependency to the repository dll – Camilo Terevinto Oct 19 '20 at 19:58
  • Another layer of abstraction might be the way to go? like you said interacting with services. that being said Sharing a Common or Core Library is a very common practice. – Retic Oct 19 '20 at 20:15
  • You don't need to explicitly reference the repo project, ASP.NET Core implicitly references it indirectly. – Ian Kemp Oct 19 '20 at 22:19
  • 1
    There isn't a great way but if you absolutely cannot trust your team to sniff out architecture erosion like unwanted namespacing during a pull request, and can't use other DI containers that do solve this, consider something like https://github.com/BenMorris/NetArchTest – Ben Sampica Oct 20 '20 at 00:20
  • Thanks everyone! It looks like a duplicate indeed, thanks @Steven. I was unable to google for that one. Should I delete this question? – Alex Buyny Oct 20 '20 at 20:50

1 Answers1

0

What I would recommend is to strongly consider placing your repository interfaces within a “domain layer” such that your web project references only the domain project. Then, you can just mock the repository when testing. Once you are ready to implement repository, you might then have a strong motivation to add the reference to the concrete repository within the web project since you want to DI inject the concrete implementation (you’ll have to reference data layer at this point since DI needs to know what type to inject when classes setup the constructors for this)

Judy007
  • 5,484
  • 4
  • 46
  • 68