Mapper example
Service can be used as a simple mapper.
// Create car factory
Action<IQuery<String, Car>> carFactory = q => q.Response.SetValue(new Car(q.Request));
// Create car service
IService<string, Car> carService = Services.Create<string, Car>(carFactory, CachePolicies.ToCache);
// Get-or-create car record
Car carRecord1 = carService.GetRequired("DKG-313");
// Assign owner
carRecord1.Owner = "Aku";
// Get cached record
Car carRecord = carService.GetRequired("DKG-313");
// Print owner
Console.WriteLine(carRecord);
// Car { Register = DKG-313, Owner = Aku }
/// <summary>Car record</summary>
public record Car
{
/// <summary>Register number, immutable</summary>
public string Register { get; init; }
/// <summary>Owner of the car, mutable</summary>
public string? Owner { get; set; }
/// <summary>Create car for <paramref name="register"/>.</summary>
public Car(string register) => Register = register;
}
Entry be disconnected from cache.
// Disconnect car record from cache
(carService as IEntryProvider).GetEntryCache().TryDisconnect("DKG-313");
Full Example
Full example
using System;
using Avalanche.Service;
public class examples_mapper
{
public static void Run()
{
// <1>
// Create car factory
Action<IQuery<String, Car>> carFactory = q => q.Response.SetValue(new Car(q.Request));
// Create car service
IService<string, Car> carService = Services.Create<string, Car>(carFactory, CachePolicies.ToCache);
// Get-or-create car record
Car carRecord1 = carService.GetRequired("DKG-313");
// Assign owner
carRecord1.Owner = "Aku";
// Get cached record
Car carRecord = carService.GetRequired("DKG-313");
// Print owner
Console.WriteLine(carRecord);
// Car { Register = DKG-313, Owner = Aku }
// </1>
// <3>
// Disconnect car record from cache
(carService as IEntryProvider).GetEntryCache().TryDisconnect("DKG-313");
// </3>
}
// <2>
/// <summary>Car record</summary>
public record Car
{
/// <summary>Register number, immutable</summary>
public string Register { get; init; }
/// <summary>Owner of the car, mutable</summary>
public string? Owner { get; set; }
/// <summary>Create car for <paramref name="register"/>.</summary>
public Car(string register) => Register = register;
}
// </2>
}