-
Notifications
You must be signed in to change notification settings - Fork 10.5k
[Blazor] Introduce IComponentPropertyActivator for property injection #64595
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
Open
javiercn
wants to merge
1
commit into
main
Choose a base branch
from
javiercn/component-property-injection
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+376
−123
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
106 changes: 106 additions & 0 deletions
106
src/Components/Components/src/DefaultComponentPropertyActivator.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,106 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
|
|
||
| using System.Collections.Concurrent; | ||
| using System.Diagnostics.CodeAnalysis; | ||
| using System.Reflection; | ||
| using Microsoft.AspNetCore.Components.HotReload; | ||
| using Microsoft.AspNetCore.Components.Reflection; | ||
| using Microsoft.Extensions.DependencyInjection; | ||
| using static Microsoft.AspNetCore.Internal.LinkerFlags; | ||
|
|
||
| namespace Microsoft.AspNetCore.Components; | ||
|
|
||
| internal sealed class DefaultComponentPropertyActivator : IComponentPropertyActivator | ||
| { | ||
| private const BindingFlags InjectablePropertyBindingFlags | ||
| = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; | ||
|
|
||
| private static readonly ConcurrentDictionary<Type, Action<IServiceProvider, IComponent>> _cachedPropertyActivators = new(); | ||
|
|
||
| static DefaultComponentPropertyActivator() | ||
| { | ||
| if (HotReloadManager.Default.MetadataUpdateSupported) | ||
| { | ||
| HotReloadManager.Default.OnDeltaApplied += ClearCache; | ||
| } | ||
| } | ||
|
|
||
| public static void ClearCache() => _cachedPropertyActivators.Clear(); | ||
|
|
||
| /// <inheritdoc /> | ||
| public Action<IServiceProvider, IComponent> GetActivator( | ||
| [DynamicallyAccessedMembers(Component)] Type componentType) | ||
| { | ||
| // Unfortunately we can't use 'GetOrAdd' here because the DynamicallyAccessedMembers annotation doesn't flow through to the | ||
| // callback, so it becomes an IL2111 warning. The following is equivalent and thread-safe because it's a ConcurrentDictionary | ||
| // and it doesn't matter if we build a cache entry more than once. | ||
| if (!_cachedPropertyActivators.TryGetValue(componentType, out var activator)) | ||
| { | ||
| activator = CreatePropertyActivator(componentType); | ||
| _cachedPropertyActivators.TryAdd(componentType, activator); | ||
| } | ||
|
|
||
| return activator; | ||
| } | ||
|
|
||
| private static Action<IServiceProvider, IComponent> CreatePropertyActivator( | ||
| [DynamicallyAccessedMembers(Component)] Type type) | ||
| { | ||
| // Do all the reflection up front | ||
| List<(string name, Type propertyType, PropertySetter setter, object? serviceKey)>? injectables = null; | ||
| foreach (var property in MemberAssignment.GetPropertiesIncludingInherited(type, InjectablePropertyBindingFlags)) | ||
| { | ||
| var injectAttribute = property.GetCustomAttribute<InjectAttribute>(); | ||
| if (injectAttribute is null) | ||
| { | ||
| continue; | ||
| } | ||
|
|
||
| injectables ??= new(); | ||
| injectables.Add((property.Name, property.PropertyType, new PropertySetter(type, property), injectAttribute.Key)); | ||
| } | ||
|
|
||
| if (injectables is null) | ||
| { | ||
| return static (_, _) => { }; | ||
| } | ||
|
|
||
| return Initialize; | ||
|
|
||
| // Return an action whose closure can write all the injected properties | ||
| // without any further reflection calls (just typecasts) | ||
| void Initialize(IServiceProvider serviceProvider, IComponent component) | ||
| { | ||
| foreach (var (propertyName, propertyType, setter, serviceKey) in injectables) | ||
| { | ||
| object? serviceInstance; | ||
|
|
||
| if (serviceKey is not null) | ||
| { | ||
| if (serviceProvider is not IKeyedServiceProvider keyedServiceProvider) | ||
| { | ||
| throw new InvalidOperationException($"Cannot provide a value for property " + | ||
| $"'{propertyName}' on type '{type.FullName}'. The service provider " + | ||
| $"does not implement '{nameof(IKeyedServiceProvider)}' and therefore " + | ||
| $"cannot provide keyed services."); | ||
| } | ||
|
|
||
| serviceInstance = keyedServiceProvider.GetKeyedService(propertyType, serviceKey) | ||
| ?? throw new InvalidOperationException($"Cannot provide a value for property " + | ||
| $"'{propertyName}' on type '{type.FullName}'. There is no " + | ||
| $"registered keyed service of type '{propertyType}' with key '{serviceKey}'."); | ||
| } | ||
| else | ||
| { | ||
| serviceInstance = serviceProvider.GetService(propertyType) | ||
| ?? throw new InvalidOperationException($"Cannot provide a value for property " + | ||
| $"'{propertyName}' on type '{type.FullName}'. There is no " + | ||
| $"registered service of type '{propertyType}'."); | ||
| } | ||
|
|
||
| setter.SetValue(component, serviceInstance); | ||
| } | ||
| } | ||
| } | ||
| } | ||
29 changes: 29 additions & 0 deletions
29
src/Components/Components/src/IComponentPropertyActivator.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,29 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
|
|
||
| using System.Diagnostics.CodeAnalysis; | ||
| using static Microsoft.AspNetCore.Internal.LinkerFlags; | ||
|
|
||
| namespace Microsoft.AspNetCore.Components; | ||
|
|
||
| /// <summary> | ||
| /// Provides a mechanism for activating properties on Blazor component instances. | ||
| /// </summary> | ||
| /// <remarks> | ||
| /// This interface allows customization of how properties marked with <see cref="InjectAttribute"/> | ||
| /// are populated on component instances. The default implementation uses the <see cref="IServiceProvider"/> | ||
| /// to resolve services for injection. | ||
| /// </remarks> | ||
| public interface IComponentPropertyActivator | ||
| { | ||
| /// <summary> | ||
| /// Gets a delegate that activates properties on a component of the specified type. | ||
| /// </summary> | ||
| /// <param name="componentType">The type of component to create an activator for.</param> | ||
| /// <returns> | ||
| /// A delegate that takes an <see cref="IServiceProvider"/> and an <see cref="IComponent"/> | ||
| /// instance, and populates the component's injectable properties. | ||
| /// </returns> | ||
| Action<IServiceProvider, IComponent> GetActivator( | ||
| [DynamicallyAccessedMembers(Component)] Type componentType); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1 +1,3 @@ | ||
| #nullable enable | ||
| Microsoft.AspNetCore.Components.IComponentPropertyActivator | ||
| Microsoft.AspNetCore.Components.IComponentPropertyActivator.GetActivator(System.Type! componentType) -> System.Action<System.IServiceProvider!, Microsoft.AspNetCore.Components.IComponent!>! |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.