Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

In SSR, supply HttpContext as cascading value #50253

Merged
merged 5 commits into from
Aug 23, 2023
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
Original file line number Diff line number Diff line change
Expand Up @@ -20,5 +20,5 @@ public sealed class CascadingParameterAttribute : CascadingParameterAttributeBas
/// <see cref="CascadingValue{T}"/> that supplies a value with a compatible
/// type.
/// </summary>
public override string? Name { get; set; }
public string? Name { get; set; }
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,6 @@ namespace Microsoft.AspNetCore.Components;
/// </summary>
public abstract class CascadingParameterAttributeBase : Attribute
{
/// <summary>
/// Gets or sets the name for the parameter, which correlates to the name
/// of a cascading value.
/// </summary>
public abstract string? Name { get; set; }

/// <summary>
/// Gets a flag indicating whether the cascading parameter should
/// be supplied only once per component.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// The .NET Foundation licenses this file to you under the MIT license.

using Microsoft.AspNetCore.Components;
using Microsoft.Extensions.DependencyInjection.Extensions;

namespace Microsoft.Extensions.DependencyInjection;

Expand Down Expand Up @@ -50,4 +51,59 @@ public static IServiceCollection AddCascadingValue<TValue>(
public static IServiceCollection AddCascadingValue<TValue>(
this IServiceCollection serviceCollection, Func<IServiceProvider, CascadingValueSource<TValue>> sourceFactory)
=> serviceCollection.AddScoped<ICascadingValueSupplier>(sourceFactory);

/// <summary>
/// Adds a cascading value to the <paramref name="serviceCollection"/>, if none is already registered
/// with the value type. This is equivalent to having a fixed <see cref="CascadingValue{TValue}"/> at
/// the root of the component hierarchy.
/// </summary>
/// <typeparam name="TValue">The value type.</typeparam>
/// <param name="serviceCollection">The <see cref="IServiceCollection"/>.</param>
/// <param name="valueFactory">A callback that supplies a fixed value within each service provider scope.</param>
/// <returns>The <see cref="IServiceCollection"/>.</returns>
public static void TryAddCascadingValue<TValue>(
this IServiceCollection serviceCollection, Func<IServiceProvider, TValue> valueFactory)
{
serviceCollection.TryAddEnumerable(
ServiceDescriptor.Scoped<ICascadingValueSupplier, CascadingValueSource<TValue>>(
sp => new CascadingValueSource<TValue>(() => valueFactory(sp), isFixed: true)));
}

/// <summary>
/// Adds a cascading value to the <paramref name="serviceCollection"/>, if none is already registered
/// with the value type, regardless of the <paramref name="name"/>. This is equivalent to having a fixed
/// <see cref="CascadingValue{TValue}"/> at the root of the component hierarchy.
/// </summary>
/// <typeparam name="TValue">The value type.</typeparam>
/// <param name="serviceCollection">The <see cref="IServiceCollection"/>.</param>
/// <param name="name">A name for the cascading value. If set, <see cref="CascadingParameterAttribute"/> can be configured to match based on this name.</param>
/// <param name="valueFactory">A callback that supplies a fixed value within each service provider scope.</param>
/// <returns>The <see cref="IServiceCollection"/>.</returns>
public static void TryAddCascadingValue<TValue>(
this IServiceCollection serviceCollection, string name, Func<IServiceProvider, TValue> valueFactory)
{
serviceCollection.TryAddEnumerable(
ServiceDescriptor.Scoped<ICascadingValueSupplier, CascadingValueSource<TValue>>(
sp => new CascadingValueSource<TValue>(name, () => valueFactory(sp), isFixed: true)));
}

/// <summary>
/// Adds a cascading value to the <paramref name="serviceCollection"/>, if none is already registered
/// with the value type. This is equivalent to having a fixed <see cref="CascadingValue{TValue}"/> at
/// the root of the component hierarchy.
///
/// With this overload, you can supply a <see cref="CascadingValueSource{TValue}"/> which allows you
/// to notify about updates to the value later, causing recipients to re-render. This overload should
/// only be used if you plan to update the value dynamically.
/// </summary>
/// <typeparam name="TValue">The value type.</typeparam>
/// <param name="serviceCollection">The <see cref="IServiceCollection"/>.</param>
/// <param name="sourceFactory">A callback that supplies a <see cref="CascadingValueSource{TValue}"/> within each service provider scope.</param>
/// <returns>The <see cref="IServiceCollection"/>.</returns>
public static void TryAddCascadingValue<TValue>(
this IServiceCollection serviceCollection, Func<IServiceProvider, CascadingValueSource<TValue>> sourceFactory)
{
serviceCollection.TryAddEnumerable(
ServiceDescriptor.Scoped<ICascadingValueSupplier, CascadingValueSource<TValue>>(sourceFactory));
}
}
13 changes: 3 additions & 10 deletions src/Components/Components/src/PublicAPI.Unshipped.txt
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
#nullable enable
abstract Microsoft.AspNetCore.Components.CascadingParameterAttributeBase.Name.get -> string?
abstract Microsoft.AspNetCore.Components.CascadingParameterAttributeBase.Name.set -> void
abstract Microsoft.AspNetCore.Components.RenderModeAttribute.Mode.get -> Microsoft.AspNetCore.Components.IComponentRenderMode!
Microsoft.AspNetCore.Components.CascadingParameterAttributeBase
Microsoft.AspNetCore.Components.CascadingParameterAttributeBase.CascadingParameterAttributeBase() -> void
Expand Down Expand Up @@ -83,24 +81,19 @@ Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder.AddComponentParamete
Microsoft.AspNetCore.Components.StreamRenderingAttribute
Microsoft.AspNetCore.Components.StreamRenderingAttribute.Enabled.get -> bool
Microsoft.AspNetCore.Components.StreamRenderingAttribute.StreamRenderingAttribute(bool enabled) -> void
*REMOVED*Microsoft.AspNetCore.Components.CascadingParameterAttribute.Name.get -> string?
*REMOVED*Microsoft.AspNetCore.Components.CascadingParameterAttribute.Name.set -> void
Microsoft.AspNetCore.Components.SupplyParameterFromQueryProviderServiceCollectionExtensions
Microsoft.Extensions.DependencyInjection.CascadingValueServiceCollectionExtensions
override Microsoft.AspNetCore.Components.CascadingParameterAttribute.Name.get -> string?
override Microsoft.AspNetCore.Components.CascadingParameterAttribute.Name.set -> void
override Microsoft.AspNetCore.Components.EventCallback.GetHashCode() -> int
override Microsoft.AspNetCore.Components.EventCallback.Equals(object? obj) -> bool
override Microsoft.AspNetCore.Components.EventCallback<TValue>.GetHashCode() -> int
override Microsoft.AspNetCore.Components.EventCallback<TValue>.Equals(object? obj) -> bool
*REMOVED*Microsoft.AspNetCore.Components.SupplyParameterFromQueryAttribute.Name.get -> string?
*REMOVED*Microsoft.AspNetCore.Components.SupplyParameterFromQueryAttribute.Name.set -> void
override Microsoft.AspNetCore.Components.SupplyParameterFromQueryAttribute.Name.get -> string?
override Microsoft.AspNetCore.Components.SupplyParameterFromQueryAttribute.Name.set -> void
static Microsoft.AspNetCore.Components.SupplyParameterFromQueryProviderServiceCollectionExtensions.AddSupplyValueFromQueryProvider(this Microsoft.Extensions.DependencyInjection.IServiceCollection! services) -> Microsoft.Extensions.DependencyInjection.IServiceCollection!
static Microsoft.Extensions.DependencyInjection.CascadingValueServiceCollectionExtensions.AddCascadingValue<TValue>(this Microsoft.Extensions.DependencyInjection.IServiceCollection! serviceCollection, string! name, System.Func<System.IServiceProvider!, TValue>! valueFactory) -> Microsoft.Extensions.DependencyInjection.IServiceCollection!
static Microsoft.Extensions.DependencyInjection.CascadingValueServiceCollectionExtensions.AddCascadingValue<TValue>(this Microsoft.Extensions.DependencyInjection.IServiceCollection! serviceCollection, System.Func<System.IServiceProvider!, Microsoft.AspNetCore.Components.CascadingValueSource<TValue>!>! sourceFactory) -> Microsoft.Extensions.DependencyInjection.IServiceCollection!
static Microsoft.Extensions.DependencyInjection.CascadingValueServiceCollectionExtensions.AddCascadingValue<TValue>(this Microsoft.Extensions.DependencyInjection.IServiceCollection! serviceCollection, System.Func<System.IServiceProvider!, TValue>! valueFactory) -> Microsoft.Extensions.DependencyInjection.IServiceCollection!
static Microsoft.Extensions.DependencyInjection.CascadingValueServiceCollectionExtensions.TryAddCascadingValue<TValue>(this Microsoft.Extensions.DependencyInjection.IServiceCollection! serviceCollection, string! name, System.Func<System.IServiceProvider!, TValue>! valueFactory) -> void
static Microsoft.Extensions.DependencyInjection.CascadingValueServiceCollectionExtensions.TryAddCascadingValue<TValue>(this Microsoft.Extensions.DependencyInjection.IServiceCollection! serviceCollection, System.Func<System.IServiceProvider!, Microsoft.AspNetCore.Components.CascadingValueSource<TValue>!>! sourceFactory) -> void
static Microsoft.Extensions.DependencyInjection.CascadingValueServiceCollectionExtensions.TryAddCascadingValue<TValue>(this Microsoft.Extensions.DependencyInjection.IServiceCollection! serviceCollection, System.Func<System.IServiceProvider!, TValue>! valueFactory) -> void
virtual Microsoft.AspNetCore.Components.NavigationManager.Refresh(bool forceReload = false) -> void
virtual Microsoft.AspNetCore.Components.Rendering.ComponentState.DisposeAsync() -> System.Threading.Tasks.ValueTask
virtual Microsoft.AspNetCore.Components.RenderTree.Renderer.AddPendingTask(Microsoft.AspNetCore.Components.Rendering.ComponentState? componentState, System.Threading.Tasks.Task! task) -> void
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -184,8 +184,7 @@ private static void ThrowForUnknownIncomingParameterName([DynamicallyAccessedMem
{
throw new InvalidOperationException(
$"Object of type '{targetType.FullName}' has a property matching the name '{parameterName}', " +
$"but it does not have [{nameof(ParameterAttribute)}], [{nameof(CascadingParameterAttribute)}] or " +
$"[SupplyParameterFromFormAttribute] applied.");
$"but it does not have [Parameter], [CascadingParameter], or any other parameter-supplying attribute.");
}
else
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,5 +14,5 @@ public sealed class SupplyParameterFromQueryAttribute : CascadingParameterAttrib
/// Gets or sets the name of the querystring parameter. If null, the querystring
/// parameter is assumed to have the same name as the associated property.
/// </summary>
public override string? Name { get; set; }
public string? Name { get; set; }
}
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,8 @@ public bool CanSupplyValue(in CascadingParameterInfo parameterInfo)
UpdateQueryParameters();
}

var queryParameterName = parameterInfo.Attribute.Name ?? parameterInfo.PropertyName;
var attribute = (SupplyParameterFromQueryAttribute)parameterInfo.Attribute; // Must be a valid cast because we check in CanSupplyValue
var queryParameterName = attribute.Name ?? parameterInfo.PropertyName;
return _queryParameterValueSupplier.GetQueryParameterValue(parameterInfo.PropertyType, queryParameterName);
}

Expand Down
18 changes: 0 additions & 18 deletions src/Components/Components/test/CascadingParameterStateTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -476,8 +476,6 @@ class ComponentWithNamedCascadingParam : TestComponentBase

class SupplyParameterWithSingleDeliveryAttribute : CascadingParameterAttributeBase
{
public override string Name { get; set; }

internal override bool SingleDelivery => true;
}

Expand Down Expand Up @@ -523,19 +521,3 @@ public TestNavigationManager()
}
}
}

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public sealed class SupplyParameterFromFormAttribute : CascadingParameterAttributeBase
{
/// <summary>
/// Gets or sets the name for the parameter. The name is used to match
/// the form data and decide whether or not the value needs to be bound.
/// </summary>
public override string Name { get; set; }

/// <summary>
/// Gets or sets the name for the handler. The name is used to match
/// the form data and decide whether or not the value needs to be bound.
/// </summary>
public string Handler { get; set; }
}
56 changes: 50 additions & 6 deletions src/Components/Components/test/CascadingParameterTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -727,15 +727,58 @@ public void OmitsSingleDeliveryCascadingParametersWhenUpdatingDirectParameters()
});
}

[Fact]
public void CanUseTryAddPatternForCascadingValuesInServiceCollection_ValueFactory()
{
// Arrange
var services = new ServiceCollection();

// Act
services.TryAddCascadingValue(_ => new Type1());
services.TryAddCascadingValue(_ => new Type1());
services.TryAddCascadingValue(_ => new Type2());

// Assert
Assert.Equal(2, services.Count());
}

[Fact]
public void CanUseTryAddPatternForCascadingValuesInServiceCollection_NamedValueFactory()
{
// Arrange
var services = new ServiceCollection();

// Act
services.TryAddCascadingValue("Name1", _ => new Type1());
services.TryAddCascadingValue("Name2", _ => new Type1());
services.TryAddCascadingValue("Name3", _ => new Type2());

// Assert
Assert.Equal(2, services.Count());
}

[Fact]
public void CanUseTryAddPatternForCascadingValuesInServiceCollection_CascadingValueSource()
{
// Arrange
var services = new ServiceCollection();

// Act
services.TryAddCascadingValue(_ => new CascadingValueSource<Type1>("Name1", new Type1(), false));
services.TryAddCascadingValue(_ => new CascadingValueSource<Type1>("Name2", new Type1(), false));
services.TryAddCascadingValue(_ => new CascadingValueSource<Type2>("Name3", new Type2(), false));

// Assert
Assert.Equal(2, services.Count());
}

private class SingleDeliveryValue(string text)
{
public string Text => text;
}

private class SingleDeliveryCascadingParameterAttribute : CascadingParameterAttributeBase
{
public override string Name { get; set; }

internal override bool SingleDelivery => true;
}

Expand Down Expand Up @@ -852,13 +895,11 @@ class SecondCascadingParameterConsumerComponent<T1, T2> : CascadingParameterCons
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
class CustomCascadingParameter1Attribute : CascadingParameterAttributeBase
{
public override string Name { get; set; }
}

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
class CustomCascadingParameter2Attribute : CascadingParameterAttributeBase
{
public override string Name { get; set; }
}

class CustomCascadingValueProducer<TAttribute> : AutoRenderComponent, ICascadingValueSupplier
Expand Down Expand Up @@ -904,7 +945,7 @@ void ICascadingValueSupplier.Unsubscribe(ComponentState subscriber, in Cascading

class CustomCascadingValueConsumer1 : AutoRenderComponent
{
[CustomCascadingParameter1(Name = nameof(Value))]
[CustomCascadingParameter1]
public object Value { get; set; }

protected override void BuildRenderTree(RenderTreeBuilder builder)
Expand All @@ -915,7 +956,7 @@ protected override void BuildRenderTree(RenderTreeBuilder builder)

class CustomCascadingValueConsumer2 : AutoRenderComponent
{
[CustomCascadingParameter2(Name = nameof(Value))]
[CustomCascadingParameter2]
public object Value { get; set; }

protected override void BuildRenderTree(RenderTreeBuilder builder)
Expand Down Expand Up @@ -944,4 +985,7 @@ public void ChangeValue(string newValue)
StringValue = newValue;
}
}

class Type1 { }
class Type2 { }
}
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,7 @@ public void IncomingParameterMatchesPropertyNotDeclaredAsParameter_Throws()
Assert.Equal(default, target.IntProp);
Assert.Equal(
$"Object of type '{typeof(HasPropertyWithoutParameterAttribute).FullName}' has a property matching the name '{nameof(HasPropertyWithoutParameterAttribute.IntProp)}', " +
$"but it does not have [{nameof(ParameterAttribute)}], [{nameof(CascadingParameterAttribute)}] or [{nameof(SupplyParameterFromFormAttribute)}] applied.",
"but it does not have [Parameter], [CascadingParameter], or any other parameter-supplying attribute.",
ex.Message);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ public static IRazorComponentsBuilder AddRazorComponents(this IServiceCollection
services.TryAddScoped<EndpointRoutingStateProvider>();
services.TryAddScoped<IRoutingStateProvider>(sp => sp.GetRequiredService<EndpointRoutingStateProvider>());
services.AddSupplyValueFromQueryProvider();
services.TryAddCascadingValue(sp => sp.GetRequiredService<EndpointHtmlRenderer>().HttpContext);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we always register an EndpointHtmlRenderer? Should this be sp.GetService?.HttpContext`?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If we're running this code, we do always register it - that's on line 53 above.


// Form handling
services.AddSupplyValueFromFormProvider();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,8 @@ public EndpointHtmlRenderer(IServiceProvider serviceProvider, ILoggerFactory log
_services = serviceProvider;
}

internal HttpContext? HttpContext => _httpContext;

private void SetHttpContext(HttpContext httpContext)
{
if (_httpContext is null)
Expand Down
Loading