IServiceCollection 覆盖单个构造函数参数

IServiceCollection override a single constructor argument

我有一个 class 接受三个构造函数参数。在我的组合根中,我只想define/override三个构造函数参数中的一个;其他两个依赖项已经映射到我的 DI 容器中,应该从 IServiceProvider 创建。

有了 Ninject 我可以做这样的事情:

Bind<IMyInterface>().To<MyClass>()    
    .WithConstructorArgument("constructorArgumentName", x => "constructor argument value");

当 Ninject 创建 MyClass 时,它使用此字符串参数并自动为我注入其他两个依赖项。我在 .net 核心中遇到的问题是我无法告诉 IServiceCollection 我只想指定三个参数之一,我必须定义所有参数或 none。例如,在 .net 核心中,这是我必须做的:

services.AddTransient<IMyInterface>(x=> new MyClass("constructor argument value", new Dependency2(), new Dependency3());

我不喜欢必须创建 Dependency2 和 Dependency3 classes 的新实例;这两个 classes 可以有自己的构造函数参数。我只希望 DI 管理这些依赖项。所以我的问题是 - 在使用 IServiceCollection class?

映射 .net 核心中的依赖项时,如何覆盖单个构造函数参数

如果您不能只覆盖一个构造函数参数,那么您如何解决与 IServiceCollection 的依赖关系?我试过这样做:

services.AddTransient<IMyInterface>(x=> new MyClass("constructor argument value", serviceCollection.Resolve<IDependency2>(), serviceCollection.Resolve(IDependency3>());

但这没有用,我不知道如何使用 IServiceCollection 解决依赖关系。

试试这个:

services.AddTransient<IDependency2, Dependency2Impl>();

services.AddTransient<IDependency3, Dependency3Impl>();

services.AddTransient<IMyInterface>(provider=>
    return new MyClass("constructor argument value",
      provider.GetService<IDependency2>(),
      provider.GetService<IDependency3>());
);

示例:
服务缺点:

public SkillsService(IRepositoryBase<FeatureCategory> repositoryCategory, int categoryId)

启动:

 services.AddScoped<ISkillsService>(i => new SkillsService(services.BuildServiceProvider().GetService<IRepositoryBase<FeatureCategory>>(), AppSettingsFeatures.Skills));

对于想要通用但灵活的解决方案的任何人:https://gist.github.com/ReallyLiri/c669c60db2109554d5ce47e03613a7a9

API是

public static void AddSingletonWithConstructorParams<TService, TImplementation>(
            this IServiceCollection services,
            object paramsWithNames
        );
public static void AddSingletonWithConstructorParams(
            this IServiceCollection services,
            Type serviceType,
            Type implementationType,
            object paramsWithNames
        );
public static void AddSingletonWithConstructorParams<TService, TImplementation>(
            this IServiceCollection services,
            params object[] parameters
        );
public static void AddSingletonWithConstructorParams(
            this IServiceCollection services,
            Type serviceType,
            Type implementationType,
            params object[] parameters
        );

通过构造方法反射实现。