FivePD API

Using Dependencies

FivePD uses a Dependency Injection (DI) framework to provide access to its core services and functionalities. This is the primary way you should interact with the FivePD API. Using DI helps to write modular, testable, and maintainable code by decoupling your addon from the concrete implementations of these services.

How to Use a Service

The process is straightforward and works for your IExtension, Callout, and Menu classes.

  1. Identify the service you need from the API documentation (most services are within the FivePD.Server.Interfaces namespace).
  2. Add the service's interface as a parameter to your class's constructor.
  3. Assign the service to a private readonly field within your constructor.
  4. Use the field to call methods on the service throughout your class.

The DI container will automatically create and pass in the required service instance when your addon is loaded.

Example

In the following example, we inject the IAddonLoggerService, the IMarkerService and the PlayerList. We use the logger to print messages and the marker service to create a blip on the map when the addon starts and remove it when it stops.

using System.Threading.Tasks;
using CitizenFX.Core;
using FivePD.Server.API;
using FivePD.Server.Interfaces;
using FivePD.Common.Enums;
using FivePD.Server.UIModels.MenuModels;

namespace MyAwesomeAddon;

public class MyAwesomeExtension : IExtension
{
    private readonly IAddonLoggerService _logger;
    private readonly IMarkerService _markerService;
    private readonly PlayerList _playerList;

    private readonly List<Guid> _markers = new();

    public MyAwesomeExtension(IAddonLoggerService logger, IMarkerService markerService, PlayerList playerList)
    {
        this._logger = logger;
        this._markerService = markerService;
        this._playerList = playerList;
    }

    public Task OnStarted()
    {
        this._logger.Information("MyAwesomeExtension has been started!");

        // Create a marker for each player and store it to be removed later
        foreach (var player in this._playerList)
        {
            var markerId = this._markerService.AddMarker(player, new Marker
            {
                Type = FMarkerType.MarkerTypeVerticalCylinder,
                Position = new Vector3(1f, 1f, 1f),
                Color = new Marker.MarkerColor(255, 0, 0, 255),
                Scale = new Vector3(1f, 1f, 1f),
            });

            this._markers.Add(markerId);
        }

        return Task.CompletedTask;
    }

    public Task OnStopped()
    {
        this._logger.Information("MyAwesomeExtension has been stopped!");

        // Clean up the markers
        foreach (var markerId in this._markers)
        {
            this._markerService.RemoveMarker(markerId);
        }

        return Task.CompletedTask;
    }
}