Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ninject equivalent of Unity RegisterInstance method

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

I want to create a mock object and register it.

Thanks

like image 770
Ryu Avatar asked Aug 11 '09 04:08

Ryu


1 Answers

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.
//...
Bind<IMyType>().ToConstant(mock.Object);

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:

Bind<IMyType>.To<MyType>().Using<SingletonBehavior>();

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.

like image 148
Anderson Imes Avatar answered Nov 03 '22 00:11

Anderson Imes