Reputation: 349
I have an ASP.NET MVC 3 project using Ninject (NuGet install). I'm trying to understand how I can use it to inject dependencies into non-MVC objects.
I have some code that looks similar to below. How can I use Ninject to get a concrete instance of IStore in the object below?
public class SomeObject
{
private static IStore _store;
public static IStore CurrentStore
{
get
{
if (_store == null)
{
// Get Instance of _store.
}
return _store;
}
}
}
In Global.asax:
protected Application_BeginRequest()
{
IStore store = SomeObject.CurrentStore;
}
In NinjectWebCommon.cs:
private static void RegisterServices(IKernel kernel)
{
// Module that binds a concrete type of IStore.
kernel.Load<WebModule>();
}
Upvotes: 0
Views: 241
Reputation: 5480
It looks like this confuses the boundary between DI container & web app.
What you probably need is a class to retrieve the store. This class can then decide where to actually retrieve the store from. It would also have the initialise routine in it that could be called at startup.
This way, your Ninject Module doesn't get web app code in it, you get to configure how the store gets loaded based on context (eg, testing may be different to production).
Upvotes: 0
Reputation: 32725
For request handling the easiest way is not to do it in the global.asax but in a IHttpModule. There you can take the dependencies as constructor arguments if you add a binding for the HttpModule:
Bind<IHttpModule>().To<MyHttpModule>();
Upvotes: 1