ASP.NET Core Dependency Injection without referencing implementations

Viewed 577

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).

1 Answers

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)

Related