isebarn
isebarn

Reputation: 3940

Inject a service from a class library to another class library

I have two class libraries and a console application,

in my console application I have:

class Program
{
    static void Main(string[] args)
    {
        IConfiguration config = new ConfigurationBuilder()
        .SetBasePath(Path.Combine(Directory.GetCurrentDirectory()))
        .AddJsonFile("appsettings.json", false, true)
        .Build();

        var services = new ServiceCollection()
            .AddSingleton(provider => (IConfigurationRoot)config)
            .AddDbContext<Context>(options => options.UseNpgsql(config.GetConnectionString("DefaultConnection")))
            .AddScoped<IQueryService, QueryService>()
            .BuildServiceProvider();

        var a = new MockReader.MockDataServer();
        a.ReadData();
    }
}

One of the class libraries is a classic database project, reading/writing to the database, and that library defines and implements a service, IDataService. It defines fx the method

public List<int> getAll()

The second class library is supposed to be created by the console app and should have access to the IDataService methods

public class MockDataServer
{

    private IQueryService _queryService;
    public MockDataServer (IQueryService queryService) 
    {
        _queryService = queryService;
    }

But I dont know how to give it access/resolve properly?

Upvotes: 1

Views: 302

Answers (1)

Nkosi
Nkosi

Reputation: 247098

Add the server to the service collection as well so that the built provider is aware of how to resolve its dependencies.

//...

var services = new ServiceCollection()
    .AddSingleton(provider => (IConfigurationRoot)config)
    .AddDbContext<Context>(options => 
        options.UseNpgsql(config.GetConnectionString("DefaultConnection"))
    )
    .AddScoped<IQueryService, QueryService>()
    .AddScoped<MockDataServer>() //<-- Add server
    .BuildServiceProvider();

MockDataServer server = services.GetService<MockDataServer>();
server.ReadData();

The console in this case acts as the composition root and needs to be are of all types involved in order to perform its designed function.

Upvotes: 1

Related Questions