Ninject 和私有构造函数
我们使用 Ninject 进行 IOC。
我们所有的存储库对象都可以(并且应该)被模拟以进行单元测试。我想强制所有开发人员在与存储库交互时仅对接口进行编码。为此,我想将构造函数设为私有并创建用于构造的静态访问器工厂方法:
public class SomeRepository : ISomeRepository
{
private SomeRepository()
{
}
public static ISomeRepository Create()
{
return StandardKernel.Get<ISomeRepository>();
}
}
问题在于:如何让 Ninject 创建实际对象?我在同一个项目中有存储库接口和类
We're using Ninject for IOC.
All of our Repository objects can (and should be) mocked for unit testing. I'd like to enforce that all developers code only to interfaces when interacting with Repositories. For this, I'd like to make the constructors private and create static accessor factory methods for construction:
public class SomeRepository : ISomeRepository
{
private SomeRepository()
{
}
public static ISomeRepository Create()
{
return StandardKernel.Get<ISomeRepository>();
}
}
Problem lies in this: how do I have Ninject create the actual object? I have repository interface and class in the same project
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我们最终将进行以下操作:
在模块加载期间,我们将 StandardKernel 的 ISomeRepository 接口映射到 CreateForIOC() 方法。
这并不能阻止开发人员直接调用 CreateForIOC,但至少迫使他们 a) 为接口编写代码,b) 认识到 CreateForIOC() 可能不是实例化对象时调用的正确方法,并且至少询问有关它的问题来自首席开发人员
We're ultimately going with the following:
and during module loading, we're mapping the StandardKernel's ISomeRepository interface to CreateForIOC() method.
This does not stop developers from calling CreateForIOC directly, but at least forces them to a) code to an interface, b) realize that CreateForIOC() is probably not the right method to call when instantiating the object and at least ask a question about it from a lead developer
为什么不让 Ninject 为任何需要它的对象提供具体存储库,而不是使用私有构造函数或工厂方法呢?
Instead of either the private constructor or the factory method, why not just have Ninject provide the the concrete repository to any objects that need it?
看起来您正在尝试使用单例模式。一般来说,单例模式被认为是一种反模式,主要是因为它阻碍了单元测试。依赖注入允许您通过配置创建单例,而不必使用单例模式。
我建议您只需配置 Ninject 来创建应用程序的单个实例,而无需使用私有构造函数。
It looks like you're trying to use a singleton pattern. In general, the singleton pattern is considered an anti-pattern, largely because it hinders unit testing. Dependency injection allows you to create singletons via configuration without having to use the singleton pattern.
I would suggest that you instead, simply configure Ninject to create a single instance of your app without the private constructor.