dem-net/DEM.Net

Instantiate an ElevationService in 0.2.0

Closed this issue · 3 comments

sk-zk commented

How do I instantiate an ElevationService in 0.2.0? Previously, I did this:

class Elevation
{
    DEMDataSet dataSet;
    ElevationService elevationService;

    public Elevation()
    {
        dataSet = DEMDataSet.AW3D30;
        var gdal = new GDALVRTFileService();
        var raster = new RasterService(gdal);
        elevationService = new ElevationService(raster);
    }

...

Which doesn't work anymore, and the samples I've looked at just assume I already have an IElevationService I can pass into them.

Hi @sk-zk and thanks for reporting this.
DEM Net is written in a Dependency Injection friendly context. Sorry for not updating the samples.

Here is the quick fix :

class Elevation
{
    DEMDataSet dataSet;
    ElevationService elevationService;

    public Elevation()
    {
        dataSet = DEMDataSet.AW3D30;
        var gdal = new GDALVRTFileService();
        var raster = new RasterService( _ => gdal); // <------- FIX HERE
        elevationService = new ElevationService(raster);
    }

The Raster service needs to know what's the file source indexing system (GDAL VRT in your case, but there's also Nasa Earth Data, and FileSystem).

To setup DI in your project, change your program to the following (I suppose you run on a ConsoleApp)

using DEM.Net.Core;
using DEM.Net.Core.Datasets;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

class Program
{
    static void Main(string[] args)
    {
        // Needs the following NuGet packages
        // - Microsoft.Extensions.DependencyInjection
        // - Microsoft.Extensions.Logging.Console
        var services = new ServiceCollection()
                    .AddLogging(config =>
                    {
                        config.AddConsole(); // Log to console (colored !)
                    })
                    .AddDemNetCore()
                    .AddSingleton<ElevationApp>(); // <-- Your app gets registered here
        // Everything added to the constructor of your App from DEM.Net will be injected at runtime.
        // You can for example add an ILogger<ElevationApp> for your logging

        var provider = services.BuildServiceProvider();
        var app = provider.GetService<ElevationApp>();

        app.Run();

    }
}

class ElevationApp
{
    DEMDataSet dataSet;
    IElevationService elevationService;
     ILogger<ElevationApp> logger;

    public ElevationApp(IElevationService elevationService // <-- injected automatically
                        , ILogger<ElevationApp> logger;) // <-- injected automatically
    {
        this.elevationService = elevationService;
        this.logger = logger;
        dataSet = DEMDataSet.AW3D30;
    }

    public void Run()
    {
        logger.LogInformation("Starting ElevationApp...");
        // Your code here
    }
}
sk-zk commented

Thanks for the quick response!