IServiceCollection override a single constructor a

2019-02-14 06:58发布

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 other two dependencies have already been mapped in my DI container and should get created from the IServiceProvider.

With Ninject I could do something like this:

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

When Ninject creates MyClass it uses this string parameter and automatically injects the other two dependencies for me. The problem I'm experiencing in .net core is that I cannot tell the IServiceCollection I only want to specify one of the three arguments, I have to define all of them or none. For example, in .net core this is what I have to do:

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

I don't like having to create new instances of the Dependency2 and Dependency3 classes; these two classes could have their own constructor arguments. I just want the DI to manage those dependencies. So my question is - how do you override a single constructor argument when mapping dependencies in .net core using the IServiceCollection class?

If you can't override just a single contructor argument then how do you resolve a dependency with the IServiceCollection? I tried doing something like this:

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

But this didn't work, and I couldn't figure out how to resolve dependencies using the IServiceCollection.

2条回答
贼婆χ
2楼-- · 2019-02-14 07:01

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>());
);
查看更多
Animai°情兽
3楼-- · 2019-02-14 07:12

Example:
Service Cons.:

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

Startup:

 services.AddScoped<ISkillsService>(i => new SkillsService(services.BuildServiceProvider().GetService<IRepositoryBase<FeatureCategory>>(), AppSettingsFeatures.Skills));
查看更多
登录 后发表回答