gpt4 book ai didi

c# - Ninject 绑定(bind) 101

转载 作者:行者123 更新时间:2023-11-30 22:14:40 25 4
gpt4 key购买 nike

新手 Ninject 问题 klaxxon。

我有以下类和接口(interface),它们描述了我需要注入(inject)的依赖项,以及需要注入(inject)依赖项具体实例的依赖项。

public interface IDependency { }

public class FooDependency : IDependency { }

public class Depender
{
[Inject]
public IDependency Dependency { get; set; }

public bool DependencyIsNull()
{
return Dependency == null;
}
}

我已经使用 NinjectModule 实例设置了我的绑定(bind),就像这样。

public class Bindings : NinjectModule
{
public override void Load()
{
Bind<IDependency>().To<FooDependency>();
}
}

这是一个单元测试方法,它断言依赖项已注入(inject)到依赖项中。

[TestMethod]
public void TestMethod1()
{
var kernel = new StandardKernel(new Bindings());
var bar = new Depender();
Assert.IsFalse(bar.DependencyIsNull());
}

我显然在做一些根本性的错误,因为我本以为测试会通过,但事实并非如此。

最佳答案

您的对象不是由您的内核 创建的。一切都需要由 kernel 创建以注入(inject)依赖项:

// option a (recommended)
var kernel = new StandardKernel(new Bindings());
var bar = kernel.Get<IDependency>();
Assert.IsFalse(bar.DependencyIsNull());

// option b (not recommended.. but do-able)
var kernel = new StandardKernel(new Bindings());
var bar = new Depender();
kernel.Inject(bar); // injects after the fact
Assert.IsFalse(bar.DependencyIsNull());

此外,您的界面中应该有 DependencyIsNull 方法:

public interface IDependency {
bool DependencyIsNull();
}

关于c# - Ninject 绑定(bind) 101,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18404658/

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