gpt4 book ai didi

c# - 如何在不删除所有条件的情况下覆盖现有绑定(bind)?

转载 作者:可可西里 更新时间:2023-11-01 08:43:40 24 4
gpt4 key购买 nike

我目前面临的 Ninject 挑战是当我使用 Rebind<>() 时它删除所有 绑定(bind),即使是那些有条件的。让我在下面给你一个愚蠢的例子。基本上我在我的案例中发现的不良行为是,当调用 Rebind 时,它将删除条件 WhenInjectedInto<T>。绑定(bind)而不是仅仅覆盖非条件 Bind<T> .在契约(Contract)下方的示例中 Contract.Assert(cat is Wild);在 ctor 中将在重新绑定(bind)后失败。

有没有办法做我想做的事 - 能够保留已经注入(inject)的条件绑定(bind)并仅覆盖非条件绑定(bind)?

P.S:实际上,我正在尝试使用 DataContext 范围做一些有趣的事情,具体取决于它们被注入(inject)的位置(在请求中或在异步命令中)

void Main()
{
StandardKernel kernel = new StandardKernel();

kernel.Bind<ICat>().To<Wild>();
kernel.Bind<ICat>().To<Wild>()
.WhenInjectedInto<EvilCat>();

kernel.Rebind<ICat>().To<Domestic>();

Contract.Assert(kernel.Get<ICat>() is Domestic);
kernel.Get<EvilCat>();
}

interface ICat {}

class Domestic : ICat {}

class Wild : ICat { }

class EvilCat
{
public EvilCat(ICat cat) {
Contract.Assert(cat is Wild);
}
}

最佳答案

试试这个:

kernel.GetBindings(typeof(ICat)).
Where(binding => !binding.IsConditional).
ToList().
ForEach(
binding =>
kernel.RemoveBinding(binding)
)

kernel.Bind<ICat>().To<Domestic>();

当然,您可以在 foreach 中不使用 LINQ:

var bindings = kernel.GetBindings(typeof(ICat)).ToList();
foreach(var binding in bindings)
{
if (!binding.IsConditional)
kernel.RemoveBinding(binding);
}

kernel.Bind<ICat>().To<Domestic>();

关于c# - 如何在不删除所有条件的情况下覆盖现有绑定(bind)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13590224/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com