我的Startup是这样的:

public void ConfigureServices(IServiceCollection services)
{
    // code here
    Bootstraper.Setup(services);
}


我的Bootstraper类是这样的:

public static partial class Bootstraper
{
    // code here
    public static IServiceCollection CurrentServiceCollection { get;set;}

    public static IServiceProvider CurrentServiceProvider
    {
        get { return CurrentServiceCollection.BuildServiceProvider(); }
    }

    public static void Setup(IServiceCollection serviceCollection)
    {
        // code here
        SetupLog();
        InitializeCulture();
        InitializeDbContexts();
        RegisterDataModelRepositories();
    }


这是我的RegisterDataModelRepositories()的内容:

CurrentServiceCollection.AddTransient<IDefAccidentGroupRepository>(p => new DefAccidentGroupRepository(ApplicationMainContextId));
CurrentServiceCollection.AddTransient<IDefGenderRepository>(p => new DefGenderRepository(ApplicationMainContextId));


简而言之:我只想能够在我的方法中使用Service Locator而不解决类构造函数中的依赖关系...有没有解决的办法...。

最佳答案

依赖项注入也可以基于操作进行。

引用Dependency injection into controllers: Action Injection with FromServices


  有时,您不需要为一个控制器内的多个动作提供服务。在这种情况下,将服务作为操作方法的参数注入可能是有意义的。这是通过用属性[FromServices]标记参数来完成的


public IActionResult SomeAction([FromServices] IReportService reports) {
    //...use the report service for this action only

    return View();
}


只需确保所需的服务已在服务集合中注册即可。

services.AddTransient<IDefAccidentGroupRepository>(p => new DefAccidentGroupRepository(ApplicationMainContextId));
services.AddTransient<IDefGenderRepository>(p => new DefGenderRepository(ApplicationMainContextId));
services.AddTransient<IReportService, ReportService>().

09-30 21:21