I have a .NET 7 project where I have the following projects:
- WebApp
- Web API
- Service Layer
- Repository Layer
#1 calls #2 via HTTP requests, #2 references #3 which references #4, those 2 are project references (not microservices). So I am trying to use DI to inject service layer into Web API and repo layer into service layer. But obviously, I shouldn't have access to the repo layer in the Web API, so I created the following 2 extension methods:
// service project
namespace MyApp.Service
{
public static class ServiceCollectionExtensions
{
public static IServiceCollection AddServices(this IServiceCollection services)
{
services.AddSingleton<IMyService, MyService>();
return services;
}
}
}
// repo project
namespace MyApp.Repository
{
public static class ServiceCollectionExtensions
{
public static IServiceCollection AddRepository(this IServiceCollection services, string connectionString)
{
var settings = MongoClientSettings.FromConnectionString(connectionString);
var client = new MongoClient(settings);
services.AddSingleton<IMongoClient>(client);
services.AddSingleton<IMyRepository, MyRepository>();
return services;
}
}
}
Then in my Program.cs file:
var mongoDbConnectionString = builder.Configuration.GetConnectionString("MongoDB");
builder.Services.AddRepository(mongoDbConnectionString);
builder.Services.AddServices();
I would've just created one extension method in the service layer, but I needed to create a separate one in the repo layer since I am injecting the MongoDB client too.
I did not expect to be able to access AddRepository() in my Web API project but when I entered that class, VS automatically added using MyApp.Repository;
at the top and it was successfully able to access it... How and why? If I can access it, have broken the separation and DI and IoC practices and have a dependency on my repo layer from my Web API. I checked under Dependencies -> Projects for my Web API project and it only lists the service project...
So my questions are:
- why can I access the repo layer from my Web API layer?
- how do I prevent it?
- what is the proper way to do DI with my repo class? should I just not do DI with my MongoDB client and create one extension method in the service layer?