gpt4 book ai didi

.net - Ninject 和私有(private)构造函数

转载 作者:行者123 更新时间:2023-12-01 01:25:43 25 4
gpt4 key购买 nike

我们将 Ninject 用于 IOC。

我们所有的 Repository 对象都可以(并且应该)被模拟用于单元测试。我想强制所有开发人员在与存储库交互时仅对接口(interface)进行编码。为此,我想将构造函数设为私有(private)并为构造创建静态访问器工厂方法:

public class SomeRepository : ISomeRepository
{
private SomeRepository()
{
}
public static ISomeRepository Create()
{
return StandardKernel.Get<ISomeRepository>();
}
}

问题在于:我如何让 Ninject 创建实际对象?我在同一个项目中有存储库接口(interface)和类

最佳答案

我们最终将采用以下方法:

public class SomeRepository : ISomeRepository
{
private SomeRepository()
{
}
public static ISomeRepository CreateForIOC()
{
return new SomeRepository();
}
}

在模块加载期间,我们将 StandardKernel 的 ISomeRepository 接口(interface)映射到 CreateForIOC() 方法。

这不会阻止开发人员直接调用 CreateForIOC,但至少会迫使他们 a) 将代码写入接口(interface),b) 意识到 CreateForIOC() 可能不是在实例化对象时调用的正确方法,并且至少要问一个关于它的问题来自首席开发人员

关于.net - Ninject 和私有(private)构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7563937/

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