2017-02-22 104 views
0

在ASP.NET Core 1.0中,我試圖向BaseRepository構造器注入兩個參數。一個是SwitchContext(註冊如下,並自定義參數 - RepositoryCacheMode(只是枚舉))帶有可選參數的ASP.NET核心依賴注入

我有辦法註冊這樣的參數嗎?

services.AddTransient<RepositoryCacheMode, RepositoryCacheMode.None>(); 

或者如何獲取SwitchContext的實例來註冊BaseRepository?

public static void AddDependency(this IServiceCollection services) 
     {     
      services.AddTransient<SwitchContext, SwitchContext>(); 
      services.AddTransient<IRepository, BaseRepository>(t => new BaseRepository(// How to get instanse of SwitchContext ? // , RepositoryCacheMode.None)); 

BaseRepository的構造:

public BaseRepository(SwitchContext context, RepositoryCacheMode cacheMode = RepositoryCacheMode.FirstLevel) 
     { 
      Context = context; 
      _cacheMode = cacheMode; 
     } 
+0

我打了個你爲重複,因爲它看起來像幾乎相同的問題。唯一的區別是你使用默認值,他希望默認值爲null。這兩種方式都不起作用,並解釋了原因。 –

回答

1

tServiceProvider,所以你可以這樣做:

services.AddTransient<IRepository, BaseRepository>(
    serviceProvider => new BaseRepository(serviceProvider.GetService<SwitchContext>()) 
); 
+1

好吧,它適用於我,但我無法找到解決方法,我用(r => r。GetService ()) –

+0

@Ilya.Sulimanov啊對不起,我習慣了舊的Unity容器。我改變了答案 –