試圖找出如何最好地處理以下情形:依賴注入和工廠
假設一個RequestContext
類具有依賴於外部服務,如:
public class RequestContext : IRequestContext
{
private readonly ServiceFactory<IWeatherService> _weatherService;
public RequestContext(ServiceFactory<IWeatherService> weatherService, UserLocation location, string query)
{
_weatherService = weatherService;
...
什麼樣的依賴我是否應該在課堂上要求最終實例化RequestContext
?這可能是ServiceFactory<IWeatherService>
,但看起來不正確,或者我可以創建沿線的爲它的IRequestContextFactory
:
public class RequestContextFactory : IRequestContextFactory
{
private readonly ServiceFactory<IWeatherService> _weatherService;
public RequestContextFactory(ServiceFactory<IWeatherService> weatherService)
{
_weatherService = weatherService;
}
public RequestContext Create(UserLocation location, string query)
{
return new RequestContext(_weatherService, location, query);
}
}
然後通過構造函數注入傳遞IRequestContextFactory
。
這似乎是一個很好的方法,但這種方法的問題是,我認爲它阻礙了可發現性(開發人員必須瞭解工廠並實施它,這並不是很明顯)。
我錯過了更好/更容易發現的方式嗎?
有趣的是,我沒有想過直接注入RequestContext,因爲它的參數在每個頁面請求(ASP.NET MVC)上都會有所不同。使用NInject通過查看查詢字符串來正確地爲我實例化類是否是一個好主意?或者我會配置NInject使用返回實例的工廠,但在基本級別只需要注入RequestContext? – andreialecu 2010-06-10 13:11:49
我還不知道Ninject已經足夠回答關於這個問題的細節了,但是如果它不直接支持這個,你可以使用注入到更高級別消費者的抽象工廠自己實現這個小部分。 – 2010-06-10 13:22:33