What would be the recommended way to use Ninject to inject the same HttpClient object to all Controller instances in an application?
Currently, I am injecting an EntityFramework Database context following Adam Freeman's MVC book as follows. However, this creates a new dbContext for each controller instance, which is probably not ideal for HttpClient, since HttpClient is meant to be reused across all controllers in an MVC application.
Constructor:
public class AccountController : Controller
{
MyDBContext dbContext = new MyDBContext();
public AccountController(MyDBContext context)
{
dbContext = context;
}
...
}
And the Ninject Factory is as follows:
/// Class based on Adam Freeman's MVC book to use dependency injection to create controllers
public class NinjectControllerFactory : DefaultControllerFactory
{
private IKernel ninjectKernel;
public NinjectControllerFactory()
{
ninjectKernel = new StandardKernel();
AddBindings();
}
protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
{
return controllerType == null
? null
: (IController)ninjectKernel.Get(controllerType);
}
private void AddBindings()
{
ninjectKernel.Bind<MyDBContext>().ToSelf().InTransientScope();
}
}