Skip to content
One Last Click Docs

Pure C# Application Service

Application services can be easily created with plain C# classes that live for the lifetime of the application.

using OneLastClick.Services.Attributes;
[ApplicationService]
public class GameManager
{
public void LoadGame()
{
Debug.Log("Loading game...");
}
}

That’s all that’s required.

The package automatically discovers and registers the service when the application starts.

GameManager gameManager = ApplicationServices.Get<GameManager>();
gameManager.LoadGame();

for optional services, you can use the try method:

if(ApplicationServices.TryGet<GameManager>(out GameManager gameManager) == true)
{
gameManager.LoadGame();
}

Pure C# application services do not have to use a default constructor. If a service requires constructor arguments, the service can be created manually and registered through an application-services builder function.

public class GameManager
{
private readonly GameConfig _config;
public GameManager(GameConfig config)
{
_config = config;
}
public void LoadGame()
{
Debug.Log("Loading game...");
}
}

Because GameManager does not have a default constructor, an instance cannot be automatically created. Instead, the service needs to be constructed manually.

Application services supports registering functions that are called to configure and create services on startup. See Service Collection Builder for all registartion methods

You must register the functions before the first scene is loaded for them to be invoked and created before the applications start.

example function:

private static void RegisterApplicationServices(ServicesCollectionBuilder builder)
{
GameConfig config = CreateGameConfig();
GameManager gameManager = new GameManager(config);
builder.Register(gameManager);
}

To register a function, use the following example:

[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)]
private static void RegisterApplicationServices()
{
ApplicationServices.AddApplicationServicesBuilderFunction(RegisterApplicationServices);
}

The function receives a ServicesCollectionBuilder, which can then be used to register manually-created service instances.

The service can then be resolved normally:

GameManager gameManager = ApplicationServices.Get<GameManager>();
gameManager.LoadGame();

You do not need [ApplicationService] for a service that you manually register. The attribute is used by the source generator to discover services that it can register automatically.