IServiceCollection 覆盖单个构造函数参数 [英] IServiceCollection override a single constructor argument

查看:37
本文介绍了IServiceCollection 覆盖单个构造函数参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

使用 Ninject 我可以做这样的事情:

With Ninject I could do something like this:

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

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

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

我不喜欢必须创建 Dependency2 和 Dependency3 类的新实例;这两个类可以有自己的构造函数参数.我只希望 DI 管理这些依赖项.所以我的问题是 - 在使用 IServiceCollection 类映射 .net 核心中的依赖项时,如何覆盖单个构造函数参数?

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?

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

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

但这不起作用,我无法弄清楚如何使用 IServiceCollection 解决依赖关系.

But this didn't work, and I couldn't figure out how to resolve dependencies using the 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>());
);

这篇关于IServiceCollection 覆盖单个构造函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆