0

我有一個使用接口(IDataService)的Web服務(我們稱之爲WebSite)。 webservice項目通過硬編碼對象(DesignDataService)實現了一個「假」服務,用於開發websit,同時等待我的同事構建真正的實現(BreadDataService)。Ninject加載不同的實現

我NinjectWebCommon目前是這樣的:

private static void RegisterServices(IKernel kernel) 
{ 
    kernel.Bind<IDataService>().To<DesignDataService>(); 
} 

我要的是能夠提供我的同事的方式來測試我的web服務的BreadDataService,而我可以繼續使用DesignDataService。我無法在我的機器上使用BreadDataService,因爲它需要一些我沒有的組件(+數據庫)。

那麼,這裏有什麼方法?當前依賴關係樹是這樣的:

  • ServiceCore(定義IDataService
  • WebSite使用ServiceCore
  • BreadDataService使用ServiceCore

我不想引用裏面的WebSiteBreadDataService項目項目,我可能正在考慮在WebSite的文件夾,他們可以把BreadDataService dll和ninject取決於web.config中的某些配置。

提示?

+0

BreadDataService.dll是否總是在'WebSite'文件夾中 - 並且您需要在'web.config'中配置它,或者它也可以「配置「通過將dll放入'WebSite'文件夾並將其刪除?你知道如何配置ninject來加載其他程序集的模塊,或者你也需要幫助嗎? – BatteryBackupUnit

+0

第一個問題:任何一種方法都可以接受 第二個問題:我不確定如何回答的事實讓我覺得我不知道:D正如我所展示的,我的Ninject配置非常基本。謝謝! –

回答

1

我用qujck方法來構建這些extension methods。 主要區別在於它依賴於Ninject.Extensions.Conventions'FromAssembliesInPath方法

2

像這樣的事情會做的伎倆

  • 負載外部組件
  • 搜索的實現
  • 默認爲你設計時的版本,如果沒有找到

這裏是基本的代碼

IEnumerable<Assembly> assemblies = this.LoadAssemblies(@"C:\Temp"); 
Type implementation = FindImplementation(assemblies, typeof(IDataService)); 

IKernel kernel = new StandardKernel(); 

kernel.Bind<IDataService>().To(implementation ?? typeof(DesignDataService)); 

該方法將從一個特定的文件夾

private IEnumerable<Assembly> LoadAssemblies(string folder) 
{ 
    IEnumerable<string> dlls = 
     from file in new DirectoryInfo(folder).GetFiles() 
     where file.Extension == ".dll" 
     select file.FullName; 

    IList<Assembly> assemblies = new List<Assembly>(); 

    foreach (string dll in dlls) 
    { 
     try 
     { 
      assemblies.Add(Assembly.LoadFile(dll)); 
     } 
     catch 
     { 
     } 
    } 

    return assemblies; 
} 

加載外部組件(例如,插件),並且此方法將搜索一組組件中的一個實現。請注意,我已專門使用SingleOrDefault(),因此如果有多個實施方案會失敗。

private Type FindImplementation(
    IEnumerable<Assembly> assemblies, 
    Type serviceType) 
{ 
    var implementationType = (
     from dll in assemblies 
     from type in dll.GetExportedTypes() 
     where serviceType.IsAssignableFrom(type) 
     where !type.IsAbstract 
     where !type.IsGenericTypeDefinition 
     select type) 
     .SingleOrDefault(); 

    return implementationType; 
} 
+0

謝謝,我用你的答案作爲我的解決方案的靈感! –

+1

該代碼看起來很熟悉;-) – Steven