Take the 2-minute tour ×

Does Ninject have and equivalent method for unity's registerinstance.

I want to create a mock object and register it.


share|improve this question

2 Answers 2

up vote 12 down vote accepted

Here's the simple answer

Bind<IMyType>().ToConstant<MyType>(new MyType());

So here's an example using Moq:

var mock = new Mock<IMyType>();
//Setup your mock expectations / etc here.

Bonus answer:

I find that some people are actually just looking to create a singleton instance of a particular class, rather than actually creating it themselves (this allows the object to be created when something requests it, rather than when you are building your container). This is done like this:


In your case, since you said the word "mock", I'd assume you'd want the first rather than the second answer, but it's a good thing to know.

share|improve this answer
using Moq... var mock = new Mock<IMyType>(); Bind<IMyType>().ToConstant(mock); ConstantProvider would create an instance of Mock<IMyType>, which is not compatible with the requested service –  Ryu Aug 13 '09 at 7:03
you need to pass in MyMock.Object, not the mock itself :) –  Anderson Imes Aug 13 '09 at 15:47
I will update the sample above with the code you need –  Anderson Imes Aug 13 '09 at 16:48

Not sure what sort of mocking tool, if any, or version of Ninject you're using; however, it's worth mentioning that Ninject 2 has an extension for it that provides integration with Moq -- http://github.com/enkari/ninject.moq.

I realize this doesn't directly answer your question, Anderson's does that well, but thought it might be relevant anyway.

share|improve this answer
Nice! That might be really what he is looking for. –  Anderson Imes Aug 14 '09 at 17:20
Yeah, looks good -- haven't used it myself yet, but looking to do so at soon. –  Peter Meyer Aug 14 '09 at 21:11

Your Answer


