2010-01-09 47 views
1

我正在嘗試從Event Driven Architecture(非常有趣的方式)從這個職位的代碼。他的國際奧委會容器是統一的,我想用結構圖做這件事。統一到結構圖

他的代碼是:

public class EventSubscriptions : ISubscriptionService 
{ 
    public static void Add<T>() 
    { 
     var consumerType = typeof(T); 

     consumerType.GetInterfaces() 
        .Where(x => x.IsGenericType) 
        .Where(x => x.GetGenericTypeDefinition() == typeof(IConsumer<>)) 
        .ToList() 
        .ForEach(x => IoC.Container.RegisterType(x, 
                  consumerType, 
                  consumerType.FullName)); 
    } 

    public IEnumerable<IConsumer<T>> GetSubscriptions<T>() 
    { 
     var consumers = IoC.Container.ResolveAll(typeof(IConsumer<T>)); 
     return consumers.Cast<IConsumer<T>>(); 
    } 
} 

我有這似乎並不奏效的情況如下:我顯然不是太熟悉結構映射

public class SubscriptionService : ISubscriptionService 
{ 
    public static void Add<T>() 
    { 
     var consumerType = typeof(T); 

     consumerType.GetInterfaces() 
      .Where(x => x.IsGenericType) 
      .Where(x => x.GetGenericTypeDefinition() == typeof (IConsumer<>)) 
      .ToList().ForEach(x => ObjectFactory.Inject(consumerType, x));         
    } 

    public IEnumerable<IConsumer<T>> GetSubscriptions<T>() 
    { 
     var consumers = ObjectFactory.GetAllInstances(typeof(IConsumer<T>)); 
     return consumers.Cast<IConsumer<T>>(); 
    } 
} 

。有些鏈接或解釋我做錯了將非常感激。

更新:

從孔翰寧博士的答案,我結束了 -

public class SubscriptionService : ISubscriptionService 
{ 
    public IEnumerable<IConsumer<T>> GetSubscriptions<T>() 
    { 
     var consumers = ObjectFactory.GetAllInstances(typeof(IConsumer<T>)); 
     return consumers.Cast<IConsumer<T>>(); 
    } 
} 

然後在我的引導類被稱爲應用程序啓動我:

public static void ConfigureStuctureMap() 
     { 
      ObjectFactory.Initialize(x => 
      {  
       x.Scan(y => 
       { 
        y.Assembly("Domain");   
        y.Assembly("Website"); 
        y.AddAllTypesOf(typeof(IConsumer<>)); 
        y.WithDefaultConventions(); 
       }); 
      }); 
     } 

回答

3

儘管我不是結構圖專家,但我相信你可以用另一種方式來完成。

結構圖能夠掃描給定接口的任何給定程序集並自動註冊所有實現。我在我目前的項目中這樣做,它運作非常好。

我不記得我們使用完全相同的代碼,但你可以組裝掃描檢查出的文檔實現ITypeScanner接口

http://structuremap.sourceforge.net/ScanningAssemblies.htm

0

構建定製TypeScanner類。

public class EventSubConventionScanner : ITypeScanner 
{ 
    public void Process(Type type, PluginGraph graph) 
    { 
     Type interfaceType = type.FindInterfaceThatCloses(typeof(IConsumer<>)); 

     if (interfaceType != null) 
     { 
      graph.AddType(interfaceType, type); 
     } 
    } 
} 

後,在註冊表或初始化程序寫:

Scan(x => 
     { 
      x.With<EventSubConventionScanner>(); 
     });