2012-08-16 40 views
1

我有一個庫,旨在用於桌面應用程序和Web應用程序。Ninject指定未引用組件的綁定範圍

該庫對外部數據訪問組件的引用,該組件在桌面上應該被綁定爲單例,並且在Web上應該根據請求範圍。

  • 桌面項目引用核心項目
  • Web項目引用核心項目
  • 核心項目引用ExternalComponent

今天,我不得不這樣做的網絡客戶端上:

Bind<ExternalComponent.IDataAccessComponent>() 
    .To<ExternalComponent.DataAccessComponent() 
    .InRequestScope() 
    .WithConstructorArgument(...); 

而在桌面客戶端,相同但InSingletonScope()這迫使我的W eb和桌面應用程序來引用ExternalComponent.dll,這不是我的意圖。

如何進行綁定,以便我可以從客戶端(Web或桌面)指定我需要此外部組件的範圍,而無需客戶端引用此數據訪問組件?

我想在覈心項目上的一些方法接收客戶端需要的範圍,並設置了所有,但我找不到在Ninject API中讓我這樣做的東西。

+0

爲什麼這個引用有問題?最後,您需要確保ExternalComponent程序集存在於兩個應用程序的基本路徑中,因爲核心項目需要它。 – 2012-08-16 17:17:09

+0

因爲我想避免不必要的參考。 ExternalComponent只會被Core使用,除了ninject綁定配置之外,沒有用於客戶機引用的用例。 – 2012-08-16 18:22:00

+0

整個綁定語法是通用的。通用類型T用Bind 方法定義。如果您使用System.Type接受綁定方法或者使用對象綁定,則只能達到您想要的效果。我將轉儲一個例子作爲答案。 – 2012-08-16 18:35:30

回答

1

我不知道爲什麼這是必要的,但它使用接受System.Type的語法時,纔可能:

public class CoreModule : NinjectModule 
{ 
    public override void Load() 
    { 
     this.Extend(this.Bind(typeof(IDataAccessComponent)).To(typeof(DataAccessComponent))).WithConstructorArgument("foo", "bar"); 
    } 

    protected virtual IBindingNamedWithOrOnSyntax<object> Extend(IBindingInSyntax<object> bindingWhenInNamedWithOrOnSyntax) 
    { 
     return bindingWhenInNamedWithOrOnSyntax; 
    } 
} 

public class WebClientModule : CoreModule 
{ 
    protected override IBindingNamedWithOrOnSyntax<object> Extend(IBindingInSyntax<object> bindingWhenInNamedWithOrOnSyntax) 
    { 
     return bindingWhenInNamedWithOrOnSyntax.InRequestScope(); 
    } 
} 

public class ClientModule : CoreModule 
{ 
    protected override IBindingNamedWithOrOnSyntax<object> Extend(IBindingInSyntax<object> bindingWhenInNamedWithOrOnSyntax) 
    { 
     return bindingWhenInNamedWithOrOnSyntax.InSingletonScope(); 
    } 
} 

上述去除強結合語義。