Looking for Ninject equivalent of StructureMap's ObjectFactory.GetInstance() method - ninject

I'm using Ninject in an MVC project and I've used the autoregistration features in Ninject.Mvc and have my bindings set up in my application class. However, I have a place where I want to create an instance separate from those bindings. In StructureMap, you can do var foo = ObjectFactory.GetInstance<IFoo>(); and it will resolve it for you. Is there an equivalent in Ninject 2? I can't seem to find it anywhere.

AFAIK, NInject doesn't have static method like this so all resolving should go to some kernel.
But you can implement it easily;
class ObjectFactory
{
static IKernel kernel = new StandardKernel(.....);
public static T GetInstance<T>()
{
return kernel.Get<T>();
}
}
Although, IMO, NInject is much more useful as DI container than as service locator.

You can also use Common Service Locator as an abstraction layer for Ninject IOC which offers what you want. The advantage is that you can later switch container if it does not fit your needs anymore.
In your code you can use something like this:
ServiceLocator.Current.GetInstance<Type>();

Related

Dependency Inject with Ninject 2.0

A little question regarding Ninject.
I use a WCF 'duplex channel' to communicate with a service. The channel is defined as an interface, lets call it IMyChannel for simplicity. To instantiate a channel we use DuplexChannelFactory<IMyChannel> object's CreateChannel() method.
So far I have manage to bind the factory class with this.
Bind< DuplexChannelFactory< IMyChannel>>().ToMethod(context =>
new DuplexChannelFactory< IMyChannel>(
new MessageEndPoint(),
new NetTcpBinding(),
"net.tcp://localhost:8321")).InSingletonScope();
}
}
However I'm a little unsure how to bind the IMyChannel interface since I use Ninject to create DuplexChannelFactory<IMyChannel> so to bind IMyChannel I do Bind< IMyChannel>(). ???
This isnt really an IOC container issue.
While, in theory, you could do:
Bind<Func<IMyInterface>>().ToConstant( context => context.Kernel.Get<DCF<IMC>>().CreateChannel)
and then demand a Func<IMyInterface>() in your ctor, calling it whenever you want to create a channel.
The problem is that the object that CreateChannel() returns implements both IMyChannel and IDisposable, hence you cannot neatly use a using block around it if that's what you're going to return. This is what the tooling generates for you when you create Service Reference, and WCF OOTB doesnt offer a general mechanism here.
I personally inject a factory, and have it have a Create<T>() method that yields a wrapper object that:
implements IDisposable
has a way to call methods across the channel.
It's not injectable into a post so hopefully someone will be along soon with a nice wrapper class of this nature.
Not sure if Singleton is appropriate, but I'd have to look around to be sure.

How to manage IoC containers in tests?

I'm very new to testing and IoC containers and have two projects:
MySite.Website (MVC)
MySite.WebsiteTest
Currently I have an IoC container in my website. Should I recreate another IoC container for my test? Or is there a way to use the IoC in both?
When you have an IoC container, hopefully you will also have some sort of dependency injection going on - whether through constructor or setter injection.
The point of a unit test is to test components in isolation and doing DI goes a long way in aiding that. What you want to do is unit test each class by manually constructing it and passing it the required dependencies, not rely on container to construct it.
The point of doing that is simple. You want to isolate the SUT(System Under Test) as much as possible. If your SUT relies on another class and IoC to inject it, you are really testing three systems, not one.
Take the following example:
public class ApiController : ControllerBase {
IRequestParser m_Parser;
public ApiController(IRequestParser parser) {
m_Parser = parser;
}
public ActionResult Posts(string request) {
var postId = m_Parser.GetPostId(request);
}
}
The ApiController constructor is a dependency constructor and will get invoked by IoC container at runtime. During test, however, you want to mock IRequestParser interface and construct the controller manually.
[Test]
public void PostsShouldCallGetPostId() {
//use nmock for mocking
var requestParser = m_Mocks.NewMock<IRequestParser>();
//Set up an expectation that Posts action calls GetPostId on IRequestParser
Expect.Once.On(requestParser).Method("GetPostId").With("posts/12").Will(Return.Value(0));
var controller = new ApiController(requestParser);
controller.Posts("posts/12");
}
Testing is about real implementation. So you normally should not use IOC in your unit tests. In case you really feel needing it (one component depending on another one), using an interface to isolate the interaction and using a mocking lib (Moq is good) to mock it and do the testing.
The only chance I see IOC container is necessary for testing is in integration testing.

Can Ninject be instructed to apply context-based logic to all bindings?

We've begun using Dependency Injection recently, and we've chosen Ninject 2 (for now) as our IoC Container. As I refactor our solution to incorporate DI principles, I've run into something that bugs me a little, and I'm wondering if there's an easy way to get around it.
For our data layer, we have a whole bunch of data-access classes that inherit the same generic class (EntityMapper). While in the past we've always constructed a new instance of these classes when we needed one, they really could all be changed into Singletons. We've overridden ObjectDataSource to use Ninject to instantiate its data-access object, so any time we create an ObjectDataSource that points to one of our EntityMapper classes, Ninject will use its default self-binding strategy to inject the necessary dependencies. Since there are so many of these classes, we'd rather not have to create an explicit binding for each of our EntityMapper classes, and we'd rather not have to put a special attribute on every one of them either. However, I would like to be able to instruct Ninject to make any instance of EntityMapper into a singleton class. Something like this:
Bind(t => typeof(IEntityMapper).IsAssignableFrom(t)).InSingletonScope();
Is there any way to do this?
You can use the conventions extension to do the following
var kernel = new StandardKernel();
kernel.Scan( x=>
{
x.FromAssemblyContaining<MyEntityMapper>();
x.FromCallingAssembly();
x.WhereTypeInheritsFrom<IEntityMapper>();
x.InSingletonScope();
} );

Constructor dependency injection with NHibernate 2.1 and StructureMap

I've read somewhere that NHibernate 2.1 supports constructor dependency injection for it's entites.
How do I go about configuring StructureMap and NHibnerate 2.1 to get this up and running ?
I realize this is an old question, but in case it might be useful.
EDIT: Original posted links weren't effective for NHib 2.1, found better info.
For NHibernate 2.1, you can create an Interceptor and override the Instantiate method and have your container create your instances there. Here is an example
If you wanted to do property injection instead, you can use the same technique but do your work in the onLoad method instead.
By setting up StructureMap across all of your entities (classes etc) and then using the interface for each of those as the signature for the constructor of a class...when you instantiate the class that has a dependency in its constructor StructureMap will auto inject it for you!
[PluginFamily("Default")]
public interface IWidget1
[Pluggable("Default")]
public class Widget1 : IWidget1
[PluginFamily("Default")]
public interface IAnotherWidget
[Pluggable("Default")]
public class AnotherWidget : IAnotherWidget
{
public AnotherWidget(IWidget widget)
{
...
}
}
IAnotherWidget _anotherWidget = ObjectFactory.GetInstance<IAnotherWidget>();
Something like that!
This may be of use too: Can I replace the call to Activator.CreateInstance() in NHibernate?
And this: http://devlicio.us/blogs/billy_mccafferty/archive/2007/02/05/inject-di-container-into-domain-objects-with-nhibernate.aspx

StructureMap with WCF?

Anyone had any luck integrating StructureMap (DI Framework) with WCF?
I can return the default instance in the constructor of my WCF service like this, but obviously it is not ideal.
public MemberService()
{
this.memberRepository = StructureMap.ObjectFactory.GetInstance<IMemberRepository>();
}
I have seen this (http://www.lostechies.com/blogs/jimmy_bogard/archive/2008/07/29/integrating-structuremap-with-wcf.aspx) but have not had luck setting it up as I think it's incompatible with the latest 2.5+ release of StructureMap.
This has already been discussed here. What issues did you encounter with the example you provided? Instead of writing the code in the constructor of the service you write it in the GetInstance method of your IInstanceProvider implementation.