2010-03-04 47 views

回答

16

我讀了這篇文章,但它沒有給我相當我需要的東西。 AddAllTypesOf註冊了IRepositoryInterface的所有具體類型,但是我要求每個具體類型都使用equivilent命名對接口進行註冊。 即。

For<IMyRepository>().Use<SqlMyRepository>(); 

另外我需要爲測試存儲庫創建一些命名實例。

For<IMyRepository>().Use<TestMyRepository>().Named("Test"); 

這是我想出來的,它似乎工作,因爲我需要它。

public class SqlRepositoryConvention : StructureMap.Graph.IRegistrationConvention 
{ 
    public void Process(Type type, Registry registry) 
    { 
     // only interested in non abstract concrete types that have a matching named interface and start with Sql   
     if (type.IsAbstract || !type.IsClass || type.GetInterface(type.Name.Replace("Sql", "I")) == null) 
      return; 

     // Get interface and register (can use AddType overload method to create named types 
     Type interfaceType = type.GetInterface(type.Name.Replace("Sql","I")); 
     registry.AddType(interfaceType, type); 
    } 
} 

並實現瞭如下

Scan(cfg => 
      { 
       cfg.TheCallingAssembly(); 
       cfg.Convention<SqlRepositoryConvention>(); 
      }); 
+1

正是我需要的,謝謝 – 2010-04-22 09:22:42

1

退房http://codebetter.com/blogs/jeremy.miller/archive/2009/01/20/create-your-own-auto-registration-convention-with-structuremap.aspx

特別是,這部分

 container = new Container(x => 

     { 

      x.Scan(o => 

      { 

       o.TheCallingAssembly(); 
       o.AddAllTypesOf<IController>().NameBy(type => type.Name.Replace("Controller", "")); 

      }); 

     }); 

那麼對你來說,我覺得這樣的事情應該工作

 container = new Container(x => 

     { 

      x.Scan(o => 

      { 

       o.TheCallingAssembly(); 
       o.AddAllTypesOf<IRepository>().NameBy(type => type.Name.Replace("I", "Sql")); 

      }); 

     }); 
+0

謝謝,我給一個嘗試。 – 2010-03-04 14:03:49