2017-01-01 82 views
1

使用Ninject將相同的HttpClient對象注入應用程序中的所有Controller實例的建議方式是什麼?如何與HttpClient一起使用Ninject

目前,我正在注入一個EntityFramework數據庫上下文後亞當弗里曼的MVC書如下。但是,這爲每個控制器實例創建了一個新的dbContext,對於HttpClient來說可能並不理想,因爲HttpClient旨在在MVC應用程序的所有控制器中重用。

構造:

public class AccountController : Controller 
{ 
    MyDBContext dbContext = new MyDBContext(); 

    public AccountController(MyDBContext context) 
    { 
    dbContext = context; 
    } 

    ... 
} 

而且Ninject廠如下:

/// 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();   
    } 
} 

回答

0

你只需要改變你的配置:

ninjectKernel.Bind<MyDBContext>().ToSelf().InRequestScope(); 

有關請求作用域的更多信息請閱讀this

1

謝謝史蒂文。目前,我發現以下作品。我在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 
    } 
} 
相關問題