使用Ninject将相同的HttpClient对象注入应用程序中的所有Controller实例的推荐方法是什么?
目前,我正按照Adam Freeman的MVC书籍注入EntityFramework数据库上下文,如下所示.但是,这会为每个控制器实例创建一个新的dbContext,这可能不适合HttpClient,因为HttpClient意味着可以在MVC应用程序中的所有控制器上重用.
构造函数:
public class AccountController : Controller
{
MyDBContext dbContext = new MyDBContext();
public AccountController(MyDBContext context)
{
dbContext = context;
}
...
}
Ninject Factory如下:
/// 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();
}
}
最佳答案 谢谢史蒂文.目前,我发现以下工作.我在NinjectController中创建了一个静态HttpClient属性,并在单例范围内将其绑定为常量.
Daniel’s book有助于更好地理解Ninject.
/// Class based on Adam Freeman's MVC book to use dependency injection to create controllers
public class NinjectControllerFactory : DefaultControllerFactory
{
private IKernel ninjectKernel;
private static HttpClient WebAPIClient; // added
public NinjectControllerFactory()
{
ninjectKernel = new StandardKernel();
WebAPIClient = new HttpClient(); // added
WebAPIClient.BaseAddress = new Uri("http://localhost:1153"); // added
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();
ninjectKernel.Bind<HttpClient>().ToConstant(WebAPIClient).InSingletonScope(); // added
}
}