Skip to content

DependencyInjection

Yannik Höflich edited this page Aug 22, 2023 · 1 revision

Dependency Injection

Using dependency injection

MatrixWeb supports dependency injection. It has multiple default services that you can find under Services.

You can inject them, both into your screen generators and your own services, the same way as everywhere else, with the constructor:

public class MyScreen: IScreenGenerator{
    private readonly ConfigService _configService;
    /*
        other properties
    */

    public MyScreen(ConfigService configService){
        _configService = configService;
    }
}

Creating your own service

To create a service, you just have to implement the IService interface. It doesn't have any properties or methods that need to be implemented, it is just used, so that MatrixWeb can identify the services. Services are always implemented over their service type. Example:

public class MyService : IService{
    public void GetColor(){
        return Color.Red;
    }
}

Using it:

public class MyScreen: IScreenGenerator{
    private readonly MyService _myService;
    /*
        other properties
    */

    public MyScreen(MyService myService){
        _myService = myService;
    }

    public Task<Screen> GenerateImageAsync() { 
        var color = _myService.GetColor();
        var img = new Image<Rgb24>(16, 16, color);
        return new Screen(img, ScreenTime)
    }
}

Clone this wiki locally