Dependency injection NetCore如何在运行时更改接口的实现
我正在使用Net Core和依赖项注入,并有以下情况:Dependency injection NetCore如何在运行时更改接口的实现,dependency-injection,.net-core,Dependency Injection,.net Core,我正在使用Net Core和依赖项注入,并有以下情况: var rootInstance = container.Resolve<Root>(); rootInstance.Run(); container.Use<IGrandChild, FirstGrandChild>(); var root1Instance = parentContainer.Resolve<Root>(); root1Instance.Run(); container.Use&l
var rootInstance = container.Resolve<Root>();
rootInstance.Run();
container.Use<IGrandChild, FirstGrandChild>();
var root1Instance = parentContainer.Resolve<Root>();
root1Instance.Run();
container.Use<IGrandChild, SecondGrandChild>();
var root2Instance = parentContainer.Resolve<Root>();
root2Instance.Run();
var secondGrandChild = new SecondGrandChild()
{
Description = "Custom Description"
};
container.User<IGrandChild>(secondGrandChild);
root2Instance = parentContainer.Resolve<Root>();
root2Instance.Run();
Expected response:
# GrandChild
# FirstGrandChild
# SecondGrandChild Default
# SecondGrandChild Custom Description
var rootInstance=container.Resolve();
rootInstance.Run();
容器。使用();
var root1Instance=parentContainer.Resolve();
root1Instance.Run();
容器。使用();
var root2Instance=parentContainer.Resolve();
root2Instance.Run();
var secondgrant=新的secondgrant()
{
Description=“自定义描述”
};
容器。用户(第二个孙子);
root2Instance=parentContainer.Resolve();
root2Instance.Run();
预期答复:
#孙子
#长孙
#次级孙违约
#第二个孙子自定义描述
(使用的类别:)
我想知道是否可以通过依赖注入或其他方法来实现这一点
我尝试了许多软件包,但没有一个提供这种功能,或者我找不到一个具体的例子来说明如何实现它
- 自动传真
- 温莎城堡
- 拉马尔
- 尼尼特
- 光注入
- 简单喷射器
container.Register(
Component.For<IMyService>()
.ImplementedBy<MyServiceImpl>()
.Named("myservice.default"),
Component.For<IMyService>()
.ImplementedBy<OtherServiceImpl>()
.Named("myservice.alternative"),
);
container.Register(
用于()的组件
.由()实施
.Named(“myservice.default”),
用于()的组件
.由()实施
.Named(“myservice.alternative”),
);
根据运行时的决策解析实现:
string impName = "myservice.alternative"; // specify it based on your decision rule
IMyService service = container.Resolve<IMyService>(impName);
string impName=“myservice.alternative”//根据您的决策规则指定它
IMyService service=container.Resolve(impName);
更改引用并重建容器,一个支持多个实现的容器我更新了问题,已经尝试了许多包,但我无法实现它这是什么用户
,这不是注册依赖项的方式用户功能是什么?您通常使用服务注册。AddScoped()代码>我真的能理解为什么您首先需要这个。通常,您可以使用装饰器或工厂来解决所需的实例。但是我想说的是,使用内置的.net实现这一点最简单的方法,而不必每次都重新构建服务提供商(因为这是一个昂贵的操作)。只需注册服务,然后接收IEnumerable并自行解决它,或者不使用依赖项注入并使其成为依赖项。我理解,问题是我需要解决根对象,通过依赖项管理器解决ChildNode,默认情况下解决孙子,在某种情况下,第一个孙子和第二个孙子