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
Example:
Service Cons.:
public SkillsService(IRepositoryBase<FeatureCategory> repositoryCategory, int categoryId)
Startup:
services.AddScoped<ISkillsService>(i => new SkillsService(services.BuildServiceProvider().GetService<IRepositoryBase<FeatureCategory>>(), AppSettingsFeatures.Skills));
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>());
);
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.