I am refactoring an existing dotnet core application where in short we have a
Currently, in our webapi project, all other three projects are referenced. This implies also that in controllers, repos and services are injected and used in the controller actions.
I was in the understanding that in Controllers, we only should call services and the service would call the repositories and the repository should use the datalayer.
I am trying to refactor all of this but i want to get rid of the dependency in the WebApi project towards repository project and datalayer project.
The problem is then, when a service is called, the repos and further on the datalayer is not found anymore for further injection.
Am i totally mistaken in my setup i want ? How can I solve this so that for references i have
But i want my DI to keep on working as expected.
Am i expecting the impossible or am i totally confused? Thank to enlighten me.
In my opinion, your project references are correct.
For example, if there are 3 layers, Controllers
, BLL
, and DAL
, they should be referenced like this: Controllers -> BLL -> DAL
.
I think, there could be some problem with DI settings. For instance, in one of my projects I have Contollers project (Presentation layer) with reference to the BLL project. So, the DI for Controllers looks like:
file: Startup.cs
public void ConfigureServices(IServiceCollection services)
{
// Some settings go here ...
MapsterConfig.MapsterSetup();
services.AddControllers();
// And here I add the DI for the BLL project.
services.AddBllInfrastructure(Configuration);
}
In the BLL project, there is a DependencyInjection.cs
class:
public static class DependencyInjection
{
public static void AddBllInfrastructure(this IServiceCollection services, IConfiguration configuration)
{
MapsterConfig.MapsterSetup();
services.AddDbContext<MyDbContext>(options =>
options.UseNpgsql(configuration.GetConnectionString("DefaultConnection"), x => x.UseNetTopologySuite()));
// Repositories, come from the DAL project
services.AddScoped<IMyDbContext, MyDbContext>();
services.AddScoped<IUnitOfWork, UnitOfWork>();
// Services, located in the BLL project
services.AddTransient<IService1, Service1>();
services.AddTransient<IService2, Service2>();
}
This way it works for me, hope this helps.