Skip to content

Create components using dependency injection #5497

Closed
@scabana

Description

@scabana

From what I see, it would be changing this line: https://github.com/aspnet/Blazor/blob/5be754e75def0c4134e379a6440c6b284828f01e/src/Microsoft.AspNetCore.Blazor/Components/ComponentFactory.cs#L35

Another change would be to allow for interfaces that derives from IComponent in the language service.

The usecases are the following:

  1. Allow for code only components to use constructor injection. The property injection support was native in Asp.Net core while it was in its early stages and was later removed to make the DI simpler and more focussed. This seems to be a step backwards.

  2. Allow this pattern:

//In assembly A
public interface IMyComponent : IComponent { int SomeParameter{get;set;} }

//In assembly B
public class MyComponent: BlazorComponent, IMyComponent { }

//In the blazor app: 

//Setting up dependency injection
class Program
{
    static void Main(string[] args)
    {
        var serviceProvider = new BrowserServiceProvider(configure =>
        {
            //Potentially load implementation dynamically here
            configure.Add(ServiceDescriptor.Transient(typeof(IMyComponent), typeof(MyComponent)));
        });
        new BrowserRenderer(serviceProvider).AddComponent<App>("app");
    }
}

//in cshtml page
<IMyComponent SomeParameter="22" />

How would this be useful: it would become possible to expose components as a contract between multiple assemblies, potentially multiple repositories. This could become the base for a micro-ui architecture where each service could expose their UI components as a contract thus removing the need for a fully pre-built application and allowing dynamically loading components for A/B testing or for testing new features behind feature flags.

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions