如何为 Ninject 创建起订量提供商?
我想创建一个简单的 Ninject 提供程序,它返回 Moq'd 实例而不是具体类型。到目前为止,我的想法是:
public class NinjectMockProvider<T> : IProvider
{
public static Type Type { get { return typeof(T); } }
public object Create(IContext context)
{
Mock<T> newMock = new Mock<T>();
return newMock.Object;
}
}
但这完全是错误的,我确信我不知道我到底在做什么。任何帮助和代码示例都会很棒。我只是想要有能力做:
kernel.Bind<ISomeInterface>().ToProvider<NinjectMoqProvider<ISomeInterface>>();
或者达到这样的效果。
更新
我确实发现我可以通过使用 Ninject 的方法绑定来完成我想要的事情:
kernel.Bind<ISomeInterface>().ToMethod(x => new Mock<ISomeInterface>().Object);
我仍然想要一种更优雅的方式,我可能必须按照 Ian 的建议查看 Ninject.Moq,但如果有人有任何真实的代码示例会很棒的。
I want to create a simple Ninject provider that returns Moq'd instances instead of concrete types. So far I have this:
public class NinjectMockProvider<T> : IProvider
{
public static Type Type { get { return typeof(T); } }
public object Create(IContext context)
{
Mock<T> newMock = new Mock<T>();
return newMock.Object;
}
}
But this is all wrong I'm sure as I don't know what I'm doing really. Any help and code samples would be great. I just want the ability to do:
kernel.Bind<ISomeInterface>().ToProvider<NinjectMoqProvider<ISomeInterface>>();
or something to that effect.
Update
I did figure out that I could accomplish what I want by using Ninject's method binding:
kernel.Bind<ISomeInterface>().ToMethod(x => new Mock<ISomeInterface>().Object);
I still would like a more elegant way and I may have to check out Ninject.Moq as suggested by Ian, but if anyone has any real code examples that would be awesome.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
MockingKernel 扩展是否可以满足您的需求?它具有 Moq、RhinoMocks 和 NSubstitute 风格,并且也可在 NuGet 上使用。
Does the MockingKernel extension handle what you need? It has Moq, RhinoMocks, and NSubstitute flavors, and it is also available on NuGet.
我的解决方案总是使用以下内容:
MoqProvider
然后我还在我的内核中注册了一个
IMissingBindingResolver
。MoqMissingBindingResolver
只是为任何尚不存在绑定的服务创建一个到MoqProvider
的新绑定。MoqMissingBindingResolver
我通常还会将
Settings.DefaultScopeCallback
设置为单例,以便稍后当我需要验证某些调用是否已进行时,可以在测试中请求我的模拟对象在执行测试之前在模拟上放置或设置行为。因此,设置我的内核将如下所示:希望这有帮助。
My solution to this always just uses the following:
MoqProvider
I then also register an
IMissingBindingResolver
with my kernel. TheMoqMissingBindingResolver
simply creates a new binding to aMoqProvider
for any service for which a binding does not already exist.MoqMissingBindingResolver
I typically also set
Settings.DefaultScopeCallback
to singleton so that I can request my mocked objects in my tests later on when I need to verify certain calls have or haven't taken place, or setup behaviour on mocks prior to executing the test. So setting up my kernel will look like the following:Hope this is helpful.