2016-04-24 236 views
4

我想解決基於條件的依賴關係。解決條件依賴關係autofac

private static readonly Dictionary<string, Action<ContainerBuilder>> QRTypeDictionary = 
    new Dictionary<string, System.Action<ContainerBuilder>>() { 
      { "REST" , (builder)=> builder 
            .RegisterType<RestPublisher>() 
            .As<Publisher>()}, 
      { "DB" , (builder)=> builder 
            .RegisterType<DBPublisher>() 
            .As<Publisher>()} 
} 

我只是想確定如果這是解決依賴條件的唯一方法。我一直在使用Ninject到目前爲止並正在尋找類似如下:

kernel.Bind<Publisher>() 
     .To<DbPublisher>() 
     .When(x => Defs.AppSettings.PublisherType == "DB") 

只是想確認我在做正確的事與Autofac

+1

是'Defs.AppSettings.PublisherType'需要重新啓動應用程序來更改配置值,也可以從隨時間改變(請求之間例如)? – Steven

回答

6

我可以看到3個解決方案,以實現你想要的。

  1. 使用Lambda

    builder.RegisterType<DbPublisher>().AsSelf(); 
    builder.RegisterType<RestPublisher>().AsSelf(); 
    
    builder.Register(c => { 
        switch(Defs.AppSettings.PublisherType){ 
         case "DB": 
          c.Resolve<DbPublisher>(); 
          break; 
         case "REST": 
          c.Resolve<RestPublisher>(); 
          break; 
         default: 
          throw new NotSupportedException(); 
        } 
    }).As<IPublisher>(); 
    
  2. 使用名爲註冊

    builder.RegisterType<DbPublisher>().Named<IPublisher>("DB"); 
    builder.RegisterType<RestPublisher>().Named<IPublisher>("REST"); 
    
    builder.Register(c => { 
         var index = c.Resolve<IIndex<String, IPublisher>>(); 
         return index[Defs.AppSettings.PublisherType] 
    }.As<IPublisher>(); 
    
  3. 有條件註冊

    如果Defs.AppSettings.PublisherType在註冊過程中被定義,你可以簡單地有條件註冊你的依賴:

    switch(Defs.AppSettings.PublisherType){ 
        case "DB": 
         builder.RegisterType<DbPublisher>().As<IPublisher>(); 
         break; 
        case "REST": 
         builder.RegisterType<RestPublisher>().As<IPublisher>(); 
         break; 
        default: 
         throw new NotSupportedException(); 
    } 
    
+2

這裏是文檔的推薦方式:http://docs.autofac.org/en/latest/register/registration.html#selection-of-an-implementation-by-parameter-value所以我會追求第一個選項 – Hardrada

+0

所以我的工作是在註冊過程中完成的。所以我使用定義的字典(以減少環化複雜性)來解決發佈者。 – Farax