Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Directory.Build.props
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
JasperFx.Events, JasperFx.Events.SourceGenerator) set
<Version>$(JasperFxVersion)</Version> so they always release together. Bump this one
value to release the whole set. -->
<JasperFxVersion>2.2.5</JasperFxVersion>
<JasperFxVersion>2.2.6</JasperFxVersion>
<LangVersion>13</LangVersion>
<NoWarn>1570;1571;1572;1573;1574;1587;1591;1701;1702;1711;1735;0618</NoWarn>
<Authors>Jeremy D. Miller;Jaedyn Tonee</Authors>
Expand Down
33 changes: 32 additions & 1 deletion src/CodegenTests.FSharp/FSharpCodegenSample.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
using System.Runtime.CompilerServices;
using FSharpCodegenTarget;
using JasperFx;
using JasperFx.CodeGeneration;
using JasperFx.CodeGeneration.Frames;
using JasperFx.CodeGeneration.Model;
using JasperFx.CodeGeneration.Services;
using Microsoft.Extensions.DependencyInjection;

namespace CodegenTests.FSharp;

Expand Down Expand Up @@ -58,10 +61,30 @@ public static GeneratedAssembly BuildSampleAssembly()
AddSyncTaskHandlerType(assembly);
AddCalculatorType(assembly);
AddCastType(assembly);
AddScopedConsumerType(assembly);

return assembly;
}

/// <summary>
/// A handler that resolves a service-located <see cref="IScopedThing" /> and awaits it.
/// Exercises the scoped-DI frames: <c>use serviceScope = …CreateAsyncScope(…)</c> +
/// <c>let scopedThing = …GetRequiredService&lt;IScopedThing&gt;(serviceScope.ServiceProvider)</c>
/// (jasperfx#397). Rendered with a ServiceCollectionServerVariableSource whose IScopedThing is
/// an opaque scoped lambda factory (forcing service location).
/// </summary>
private static void AddScopedConsumerType(GeneratedAssembly assembly)
{
var type = assembly.AddType("GeneratedScopedConsumer", typeof(IScopedConsumerHandler));
var method = type.MethodFor(nameof(IScopedConsumerHandler.Handle));

// No Target — IScopedThing is resolved by the service-variable source (scoped lambda factory),
// which inserts ScopedContainerCreation + GetServiceFromScopedContainerFrame. Two awaits make
// the body a task { } (AsyncTask), exercising the `use … CreateAsyncScope()` path.
method.Frames.Add(new MethodCall(typeof(IScopedThing), nameof(IScopedThing.DoAsync)));
method.Frames.Add(new MethodCall(typeof(IScopedThing), nameof(IScopedThing.DoAsync)));
}

/// <summary>
/// Constructs a concrete <see cref="Thing" /> and passes it to a service expecting the
/// <see cref="IThing" /> interface via a <see cref="CastVariable" />. Exercises the F# cast
Expand Down Expand Up @@ -304,7 +327,15 @@ private static void AddAccumulatorType(GeneratedAssembly assembly)
/// </summary>
public static string GenerateCode()
{
return BuildSampleAssembly().GenerateFSharpCode();
// A service-variable source backed by a scoped lambda-factory registration so the
// GeneratedScopedConsumer resolves IScopedThing via service location (the scoped-DI frames).
// The other sample types use constructor injection and are unaffected by the source.
var services = new ServiceCollection();
services.AddScoped<IScopedThing>(_ => new ScopedThing());
var container = new ServiceContainer(services, services.BuildServiceProvider());
var source = new ServiceCollectionServerVariableSource(container);

return BuildSampleAssembly().GenerateFSharpCode(source);
}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,10 @@
<ProjectReference Include="..\FSharpCodegenTarget\FSharpCodegenTarget.csproj" />
</ItemGroup>

<ItemGroup>
<!-- The scoped-DI sample's generated code references IServiceScopeFactory / GetRequiredService /
CreateAsyncScope (jasperfx#397). -->
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="10.0.0" />
</ItemGroup>

</Project>
13 changes: 13 additions & 0 deletions src/CodegenTests.FSharpFixture/Generated.fs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace FSharpCodegenTarget.Generated

open FSharpCodegenTarget
open Microsoft.Extensions.DependencyInjection
open System
open System.Threading.Tasks

Expand Down Expand Up @@ -112,3 +113,15 @@ type GeneratedThingHandler(thingDescriber: FSharpCodegenTarget.ThingDescriber) =
let thing = FSharpCodegenTarget.Thing()
_thingDescriber.Describe((thing :> FSharpCodegenTarget.IThing))

type GeneratedScopedConsumer(serviceScopeFactory: Microsoft.Extensions.DependencyInjection.IServiceScopeFactory) =
let _serviceScopeFactory = serviceScopeFactory

interface FSharpCodegenTarget.IScopedConsumerHandler with
member this.Handle() : System.Threading.Tasks.Task =
task {
use serviceScope = Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.CreateAsyncScope(_serviceScopeFactory)
let scopedThing = Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService<FSharpCodegenTarget.IScopedThing>(serviceScope.ServiceProvider)
do! scopedThing.DoAsync()
do! scopedThing.DoAsync()
}

26 changes: 26 additions & 0 deletions src/FSharpCodegenTarget/Contracts.cs
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,32 @@ public interface ISyncTaskHandler
Task HandleAsync(string name);
}

/// <summary>
/// A scoped dependency + its consumer. Registering <see cref="IScopedThing" /> as an opaque
/// <c>AddScoped&lt;T&gt;(_ =&gt; …)</c> lambda factory forces JasperFx to resolve it via service
/// location, so the generated <see cref="IScopedConsumerHandler" /> implementation emits the
/// scoped-DI frames (ScopedContainerCreation + GetServiceFromScopedContainerFrame). The async
/// <c>DoAsync</c> makes the handler a <c>task { }</c> body, exercising the
/// <c>use … CreateAsyncScope()</c> path. See jasperfx#397.
/// </summary>
public interface IScopedThing
{
Task DoAsync();
}

public class ScopedThing : IScopedThing
{
public Task DoAsync()
{
return Task.CompletedTask;
}
}

public interface IScopedConsumerHandler
{
Task Handle();
}

/// <summary>
/// A base class with a public instance method (<see cref="Bump" />) and an abstract method to
/// override (<see cref="Compute" />). The generated subclass overrides <c>Compute</c> and calls the
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -77,4 +77,22 @@ public override void GenerateCode(GeneratedMethod method, ISourceWriter writer)

Next?.GenerateCode(method, writer);
}

public override void GenerateFSharpCode(GeneratedMethod method, ISourceWriter writer)
{
// NOTE: the optional Header is a C#-style code fragment (/* */ comments) and is intentionally
// not emitted on the F# path — those comment delimiters are invalid F#.
if (_serviceKey != null)
{
writer.Write(
$"{Variable.FSharpAssignmentUsage} = {typeof(ServiceProviderKeyedServiceExtensions).FSharpName()}.{nameof(ServiceProviderKeyedServiceExtensions.GetRequiredKeyedService)}<{Variable.VariableType.FSharpName()}>({_scoped.FSharpUsage}, {CodeFormatter.Write(_serviceKey)})");
}
else
{
writer.Write(
$"{Variable.FSharpAssignmentUsage} = {typeof(ServiceProviderServiceExtensions).FSharpName()}.{nameof(ServiceProviderServiceExtensions.GetRequiredService)}<{Variable.VariableType.FSharpName()}>({_scoped.FSharpUsage})");
}

Next?.GenerateFSharpCode(method, writer);
}
}
30 changes: 30 additions & 0 deletions src/JasperFx/CodeGeneration/Services/ScopedContainerCreation.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using JasperFx.CodeGeneration.Frames;
using JasperFx.CodeGeneration.Model;
using JasperFx.Core.Reflection;
using Microsoft.Extensions.DependencyInjection;

namespace JasperFx.CodeGeneration.Services;
Expand Down Expand Up @@ -104,4 +105,33 @@ public override void GenerateCode(GeneratedMethod method, ISourceWriter writer)

Next?.GenerateCode(method, writer);
}

public override void GenerateFSharpCode(GeneratedMethod method, ISourceWriter writer)
{
// F# `use` disposes the scope at the end of the enclosing scope, like `using var`. In a
// `task { }` body it binds an AsyncServiceScope (IAsyncDisposable) and the task CE's `use`
// awaits DisposeAsync. CreateAsyncScope is an extension method, so emit it as a static call to
// avoid relying on an `open`; CreateScope is a direct interface method. See jasperfx#397.
if (method.AsyncMode == AsyncMode.AsyncTask)
{
writer.Write(
$"use {Scope.Usage} = {typeof(ServiceProviderServiceExtensions).FSharpName()}.{nameof(ServiceProviderServiceExtensions.CreateAsyncScope)}({Factory.FSharpUsage})");
}
else
{
writer.Write($"use {Scope.Usage} = {Factory.FSharpUsage}.{nameof(IServiceScopeFactory.CreateScope)}()");
}

if (_postprocessors.Count > 0)
{
for (var i = 1; i < _postprocessors.Count; i++)
{
_postprocessors[i - 1].Next = _postprocessors[i];
}

_postprocessors[0].GenerateFSharpCode(method, writer);
}

Next?.GenerateFSharpCode(method, writer);
}
}
Loading