IServiceCast
IServiceCast indicates that service instance is a cast of an underlying service.
/// <summary>Indicates that the decoration implementation is a type-cast decoration.</summary>
public interface IServiceCast : IServiceDecoration { }
IServiceCastable is optional interface for those service implementations that need to customize the type-casting procedure.
/// <summary>Service that can cast to <see cref="IService{Request, Response}"/>.</summary>
public interface IServiceCastable : IServiceBase
{
/// <summary>Try cast to <see cref="IService"/>.</summary>
bool TryCast([NotNullWhen(true)] out IService castedService);
/// <summary>Try cast to <see cref="IService{Request, Response}"/>.</summary>
bool TryCast<Request, Response>([NotNullWhen(true)] out IService<Request, Response> castedService) where Request : notnull;
/// <summary>Try cast to <see cref="IService{Request, Response}"/>.</summary>
bool TryCast(Type requestType, Type responseType, [NotNullWhen(true)] out IServiceT castedService);
}
.Cast<Request,Response>() casts generic parameters. The underlying service remains the same with same cache.
// Create service
IService service = Services.Create(ServiceHandlers.Instance);
// Cast service
IService<TypeRequest, Type> typeService = service.Cast<TypeRequest, Type>();
.Cast() casts generic parameters with run-time types.
// Create service
IService<TypeRequest, Type> typeService = Services.Create<TypeRequest, Type>(ServiceHandlers.Instance);
// Cast service
IService service = typeService.Cast();
When using IService<Request, Response> the caller doesn't need specify generics parameters.
// Create service
IService service = Services.Create(ServiceHandlers.Instance);
// Cast to specific service
IService<TypeRequest, Type> typeService = service.Cast<TypeRequest, Type>();
// Issue request
Type? type = typeService.Get("System.Type");
Full Example
Full example
using System;
using System.Linq;
using Avalanche.Converter;
using Avalanche.Service;
public class service_cast
{
public static void Run()
{
{
// <10>
// Create service
IService service = Services.Create(ServiceHandlers.Instance);
// Cast service
IService<TypeRequest, Type> typeService = service.Cast<TypeRequest, Type>();
// </10>
}
{
// <11>
// Create service
IService<TypeRequest, Type> typeService = Services.Create<TypeRequest, Type>(ServiceHandlers.Instance);
// Cast service
IService service = typeService.Cast();
// </11>
}
{
// <12>
// Create service
IService service = Services.Create(ServiceHandlers.Instance);
// Cast to specific service
IService<TypeRequest, Type> typeService = service.Cast<TypeRequest, Type>();
// Issue request
Type? type = typeService.Get("System.Type");
// </12>
}
}
}