Home > Software design >  How to add Dependency of a class library which has no reference in main project in .NET Core Web API
How to add Dependency of a class library which has no reference in main project in .NET Core Web API

Time:08-30

I have two separate .net core library one for Database and other for Service. Following Repository Pattern, my main application (.Netcore web api) has only service reference as I don't want to expose my database to main project. So service has reference of Database and Wep API has reference of Service. For Service I can easily add the reference by using IServiceCollection

services.AddSingleton<IEmployeeServices, EmployeeServices>();

so I can call service from controller with dependency inject

private readonly IEmployeeServices _empServices ;

public EmployeeController(IEmployeeServices empServices)
{
   _empServices = empServices;
}

I want to call Database from Service in same manner

private readonly DbContext _context ;

public EmployeeServices(DbContext context)
{
     _context = context;
}

but then I need to assign it like following

services.AddSingleton<IDbContext , DbContext >();

so I have to add reference of Database project in my main project but I don't want to expose Database to Main Application. So, how can I register the dependency of Database project?

CodePudding user response:

You can create a different library just for this. Take a look at examples of Clean Architecture. The configuration of services is done in a dll called .Application and referenced by the WebApi. This way the WebApi does not know about any registered services, it just injects them into his ServiceCollection.

CodePudding user response:

You can create a service collection extension class in your "services project"

You will need this nuget Microsoft.Extensions.DependencyInjection.Abstractions

using Microsoft.Extensions.DependencyInjection;

public static class MyServiceCollectionExtension
{
    public static void AddDatabaseProjectServices(this IServiceCollection services)
    {
        services.AddSingleton<IDbContext,DbContext>();
    }
}

And use it in your web-api project :

services.AddDatabaseProjectServices();

Now 2 remarks :

1 ) with this extension your web-api doesn't use database project code directly but still has implicit reference on it because of service project. That's how reference and sub reference work.

The only way to forbid is using internal class (class cannot be used outside of assembly) but you won't be able to inject dependency...

2 ) .net core has a bunch of methods for adding dbcontext so it's better to use them instead of manually AddDbContext

  • Related