IServiceCollection override a single constructor argument

后端 未结 3 1904
执念已碎
执念已碎 2021-01-05 03:41

I have a class that takes three constructor arguments. In my composition root I want to define/override only one of the three constructor arguments; the oth

相关标签:
3条回答
  • 2021-01-05 04:07

    Example:
    Service Cons.:

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

    Startup:

     services.AddScoped<ISkillsService>(i => new SkillsService(services.BuildServiceProvider().GetService<IRepositoryBase<FeatureCategory>>(), AppSettingsFeatures.Skills));
    
    0 讨论(0)
  • 2021-01-05 04:11

    Try this:

    services.AddTransient<IDependency2, Dependency2Impl>();
    
    services.AddTransient<IDependency3, Dependency3Impl>();
    
    services.AddTransient<IMyInterface>(provider=>
        return new MyClass("constructor argument value",
          provider.GetService<IDependency2>(),
          provider.GetService<IDependency3>());
    );
    
    0 讨论(0)
  • 2021-01-05 04:16

    For anyone who wants a generic but flexible solution: https://gist.github.com/ReallyLiri/c669c60db2109554d5ce47e03613a7a9

    The API is

    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
            );
    

    Implemented with constructor method reflection.

    0 讨论(0)
提交回复
热议问题