Cysharp / MagicOnion

Unified Realtime/API framework for .NET platform and Unity.
MIT License
3.68k stars 417 forks source link

MagicOnion.Client.SourceGenerator #688

Closed mayuki closed 8 months ago

mayuki commented 8 months ago

This PR introduces a source generator for platform that require pre-generated client code (e.g. Unity, NativeAOT, MAUI ...). The source generator also replaces MagicOnion.Generator (moc).

Introduce MagicOnion.Client.SourceGenerator

MagicOnion.Client.SourceGenerator is shipped with MagicOnion.Client package. This means that you no longer need to the install generator tool (moc) and setup additional build steps.

Supported development environments

Usage

Define a partial class with any name of your choosing within the application. Mark it with the MagicOnionClientGeneration attribute, and specify any service type found within the assembly where you want to search for the service interface.

For example, if the MyApp.Shared assembly contains MyApp.Shared.Services.IGreeterService and MyApp.Shared.Hubs.IChatHub, specify one of them.

using MagicOnion.Client;

[MagicOnionClientGeneration(typeof(MyApp.Shared.Services.IGreeterService))]
partial class MagicOnionGeneratedClientInitializer {}

Next, configure MessagePack to use the generated MessagePack Resolver. This is the same as when using the legacy MagicOnion.Generator.

#if UNITY_2019_4_OR_NEWER
[UnityEngine.RuntimeInitializeOnLoadMethod(UnityEngine.RuntimeInitializeLoadType.BeforeSceneLoad)]
#elif NET5_0_OR_GREATER
[System.Runtime.CompilerServices.ModuleInitializer]
#endif
static void RegisterResolvers()
{
    StaticCompositeResolver.Instance.Register(
        // Add: Use MessagePack formatter resolver generated by the source generator.
        MagicOnionGeneratedClientInitializer.Resolver,
        MessagePack.Resolvers.GeneratedResolver.Instance,
        BuiltinResolver.Instance,
        PrimitiveObjectResolver.Instance
    );

    MessagePackSerializer.DefaultOptions = MessagePackSerializer.DefaultOptions
        .WithResolver(StaticCompositeResolver.Instance);
}

Source generation options

You can specify options in the named constructor of the attribute.

Breaking changes

MagicOnion.Generator (moc) has been removed. The legacy generator is no longer supported.

[!WARNING] While there is currently compatibility between MagicOnion.Client and MagicOnion.Generator (moc), there is no guarantee that this will be maintained.