Skip to content

Add support for dependency injection via constructor #32

@DevD4v3

Description

@DevD4v3

Problem reproduction

Plugin project:

[assembly: Plugin(typeof(TestService))]

namespace MyPluginProject;

public class TestService(ILogger<TestService> logger) : ITestService
{
    public int Print()
    {
        logger.LogInformation("TestService Plugin");
        return 0;
    }
}

Host application

namespace MyHostApplication;

public class PluginStartup
{
    public void ConfigureServices(WebApplicationBuilder builder)
    {
        var envConfiguration = new CPluginEnvConfiguration();
        PluginLoader.Load(envConfiguration);
        var testServices = TypeFinder.FindSubtypesOf<ITestService>();
        foreach (ITestService testService in testServices)
            testService.Print();
    }
}

If the host application is executed, the code will fail with an exception, because the method called FindSubtypesOf uses Activator.CreateInstance and the TestService type is required to have a constructor without parameters in order to create the instance.

Solution proposal

Use the Microsoft.Extensions.DependencyInjection package to create the instances and resolve the dependencies of a service.
This solves the limitation of TypeFinder.FindSubtypesOf.

API proposal

public class PluginStartup
{
    public void ConfigureServices(WebApplicationBuilder builder)
    {
        var envConfiguration = new CPluginEnvConfiguration();
        PluginLoader.Load(envConfiguration);
        builder
          .Services
          .AddSubtypesOf<ITestService>(ServiceLifetime.Transient);
    }

    public void Configure(IApplicationBuilder app)
    {
        var testServices = app
            .Services
            .GetServices<ITestService>();

        foreach (ITestService testService in testServices)
            testService.Print();
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    featureNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions