2011-07-08 42 views
2

在與雷莫Gloor(主DEV)我們Ninject配置,.NET memory profiling/risks for leaks/Ninject/Direct delegate roots的討論,我希望得到正確配置它爲ASP.NET Web表單應用程序的一些清晰度。配置Ninject

我們有一個要求,目前我們正在做以下幾點:

Bind<ISearchService>() 
    .ToMethod(ctx => new BaseSearchService(ctx.Kernel.GetDefault<IDataRetrievalService>())) 
    .InSingletonScope() 
    .Named("BaseSearchService"); 

Bind<ISearchService>() 
    .ToMethod(ctx => new HttpSearchService(
     ctx.Kernel.GetNamedOrDefault<ISearchService>("BaseSearchService"), 
     HttpContext.Current)) 
    .InRequestScope(); 

GetNamedOrDefault是我們有一個擴展方法:

public static T GetDefault<T>(this IKernel kernel) 
{ 
    return kernel.Get<T>(m => m.Name == null); 
} 

public static object GetDefault(this IKernel kernel, Type type) 
{ 
    return kernel.Get(type, m => m.Name == null); 
} 

public static T GetNamedOrDefault<T>(this IKernel kernel, string name) 
{ 
    T result = kernel.TryGet<T>(name); 

    if (result != null) 
     return result; 

    return kernel.GetDefault<T>(); 
} 

public static object GetNamedOrDefault(this IKernel kernel, Type type, string name) 
{ 
    var result = kernel.TryGet(type, name); 

    if (result != null) 
     return result; 

    return kernel.GetDefault(type); 
} 

如何最好的,我們在Ninject代表呢?我們是否應該使用「WhenParentNamed」並讓Ninject決定傳遞給構造函數的對象?

同樣,我們如何結合當前HttpContext.Current對象,使Ninject知道使用,每當一個構造函數接受一個HttpContext對象作爲它的參數之一?它應該和這裏看到的一樣嗎?

https://github.com/ninject/ninject.web.mvc/blob/master/mvc3/src/Ninject.Web.Mvc/MvcModule.cs

如果我們正在利用請求範圍的,我們應該用OnePerRequestModule,並在應用程序的Web.config配置呢?

我們應該也使用:

https://github.com/ninject/Ninject.Web.Common/blob/master/src/Ninject.Web.Common/NinjectHttpApplication.cs

爲了確保我們的對象是妥善處理?

這似乎相當簡單一些,但我只是想對大家的做法需要予以明確。

由於

回答

2

在裝飾的情況下,使用一些條件的結合(例如WhenParentNamed,WhenClassHas,WhenTargetHas或custon當)是去的最佳方式。

Bind<ISearchService>() 
    .To<BaseSearchService>() 
    .InSingletonScope() 
    .WhenParentNamed("HttpServiceDecorator"); 

Bind<ISearchService>() 
    .To<HttpSearchService>() 
    .Named("HttpServiceDecorator") 
    .InRequestScope(); 

Bind<HttpContext>().ToMethod(ctx => HttpContext.Current); 

獲得該服務的最佳方式是將其注入到需要它的類的構造函數中。沒有什麼特別需要接收HttpSearchService的實例。它將作爲默認傳遞。

由於Ninject.Web 2.2 OnePerRequestModule默認使用。所以不需要改變。

Ninject.Web.Common介紹了upcomming Ninject 2.4版本。它是所有Web擴展使用的基本組件。這意味着只要你堅持2.2,你就不能使用它。只要您切換到2.4(或2.3開發版本)就必須使用它。

+0

感謝雷莫 - 所有我想要實現的是配置綁定我的Decorator模式的實現。我希望在內核或服務定位器上始終使用Get命名,而無需命名。無論返回什麼都將由配置決定。我已經用WhenInjectedInto條件實現了這一點,但目前看不到上述情況。我認爲我需要用名稱來請求它 - HttpServiceDecorator? –

+0

不,您不必指定名稱。 HttpServiceService將被返回,因爲它是無條件的。這個名字只是元數據,並且自己完全沒有任何東西死亡。同時擺脫ServiceLocation並開始使用Ninject作爲IoC容器。請參閱http://blog.ploeh.dk/2010/02/03/ServiceLocatorIsAnAntiPattern.aspxNinject.Web Extension將允許您創建一個設計,其中您需要知道存在容器的唯一位置是配置。 –