2017-02-21 139 views
-1

查看DryIoc的wiki,看起來這些例子顯示了我需要的東西的相反方向,我想知道是否可能出現相反情況?DryIoc Register接口的很多實現

維基(部分示例)

public interface X {} 
public interface Y {} 

public class A : X, Y {} 
public class B : X, IDisposable {} 


// Registers X, Y and A itself with A implementation 
container.RegisterMany<A>(); 

... 

我想做到以下幾點

container.RegisterMany<X>(); 

// This would return one implementation each of A and B 
container.ResolveMany<X>(); 

但是它給出了這個錯誤:"Registering abstract implementation type X when it is should be concrete. Also there is not FactoryMethod to use instead."

這是可能的開箱或者我需要通過從一個程序集中獲取接口的所有實現並對其進行循環來實現它並相應註冊?

UPDATE

我看到這個例子是也許有點簡單了我的情況,但對於上面的例子,@dadhi提供的代碼的偉大工程。

這裏是一個比較「複雜」的情況下

namespace Assembly.A 
{ 
    interface IImporter { } 

    abstract class ImporterBase : IImporter { } 
} 

namespace Assembly.B 
{ 
    interface IStuffImporter : IImporter { } 
    interface IOtherImporter : IImporter { } 

    class StuffImporter : ImporterBase, IStuffImporter { } 
    class OtherImporter : ImporterBase, IOtherImporter { } 
} 

namespace Assembly.C 
{ 
    class Program 
    { 
     void Main() 
     { 
      var container = new Container(); 

      container.RegisterMany(new[] { typeof(StuffImporter).Assembly }, type => type.IsAssignableTo(typeof(IImporter)) && type.IsClass && !type.IsAbstract); 
      //I would like DryIoc to do the following behind the scenes 
      //container.Register<IStuffImporter, StuffImporter>(); 
      //container.Register<IOtherImporter, OtherImporter>(); 

      var importers = container.ResolveMany<IImporter>(); 

      importers.Should().HaveCount(2); 
      importers.First().Should().BeOfType<StuffImporter>().And.BeAssignableTo<IStuffImporter>(); 
      importers.Last().Should().BeOfType<OtherImporter>().And.BeAssignableTo<IOtherImporter>(); 
     } 
    } 
} 

將這樣的事情是可行的開箱即用的?或者我需要製作自己的擴展方法等?這真的不是什麼大問題,我很可能會在短時間內完成它,但是我想知道將來的參考資料並學習DryIoc容器。 Thnxs提前。 :)

+0

我看到更新代碼中的問題:'type => type.IsAssignableTo(typeof(IImporter))&& type.IsClass &&!type.IsAbstract' – dadhi

+0

該條件適用於**服務類型**,不適用於實現類型。因此'type => type == typeof(IImporter)'就足夠了,如果你想註冊爲'Register ()'等,或者使它成爲'type => type.IsAssignableTo(typeof(IImporter) )&& type.IsInterface'用於註冊所有'IImporter'派生的接口。回到你的謂詞,它將註冊具體類型,而不是'Register ()'。 – dadhi

回答

2

RegisterMany過載它接受組件和服務類型的條件(在wiki一個例子):

container.RegisterMany(new[] { typeof(A).Assembly }, 
    serviceTypeCondition: type => type == typeof(X)); 

上述寄存器X的所有實現從A的裝配

+0

Thnx明天將對此進行測試。 :) – furier