2009-02-27 46 views
4

我試圖讓結構圖正確地創建我的控制器,我使用DI注入到NewsController INEwsService和多數民衆贊成我唯一的構造函數。ASP.NET MVC,MVCContrib,Structuremap,讓它作爲controllerfactory工作?

public class NewsController : Controller 
{ 
    private readonly INewsService newsService; 

    public NewsController(INewsService newsService) 
    { 
     this.newsService = newsService; 
    } 

    public ActionResult List() 
    { 
     var newsArticles = newsService.GetNews(); 
     return View(newsArticles); 
    } 
} 

,我使用此代碼,啓動應用程序

public class Application : HttpApplication 
{ 
    protected void Application_Start() 
    { 
     RegisterIoC(); 
     RegisterViewEngine(ViewEngines.Engines); 
     RegisterRoutes(RouteTable.Routes); 
    } 

    public static void RegisterIoC() 
    { 
     ObjectFactory.Initialize(config => { 
      config.UseDefaultStructureMapConfigFile = false; 
      config.AddRegistry<PersistenceRegistry>(); 
      config.AddRegistry<DomainRegistry>(); 
      config.AddRegistry<ControllerRegistry>(); 
     }); 
     DependencyResolver.InitializeWith(new StructureMapDependencyResolver()); 
     ControllerBuilder.Current.SetControllerFactory(typeof(IoCControllerFactory));    
    } 
} 

但Structuremap似乎並不想注入INewsService和我得到的錯誤 此對象定義無參數的構造函數。

我錯過了什麼?

回答

6

我使用StructureMap提供的「Default Conventions」機制來避免需要單獨配置每個接口。下面是我使用,使這項工作代碼:

我的Global.asax在的Application_Start這條線(使用從MvcContrib的StructureMap廠):

protected void Application_Start() 
{ 
    RegisterRoutes(RouteTable.Routes); 
    ObjectFactory.Initialize(x => 
    { 
     x.AddRegistry(new RepositoryRegistry()); 
    }); 
    ControllerBuilder.Current.SetControllerFactory(typeof(StructureMapControllerFactory)); 
} 

而且RepositoryRegistry類看起來是這樣的:

public class RepositoryRegistry : Registry 
{ 

    public RepositoryRegistry() 
    { 
     Scan(x => 
     { 
      x.Assembly("MyAssemblyName"); 
      x.With<DefaultConventionScanner>(); 
     }); 

    } 

} 

DefaultConventionScanner查找遵循ISomethingOrOther和SomethingOrOther的命名約定的接口/類對,並自動將後者作爲前接口的具體類型關聯。

如果你不想使用默認的慣例機制,那麼你會在註冊表中添加類代碼每個接口來明確地映射到具體類型的語法:

ForRequestedType<ISomethingOrOther>().TheDefaultIsConcreteType<SomethingOrOther>(); 
0

除非我遺漏了一些東西,否則您並沒有告訴StructureMap使用什麼具體類型的INewsService。你需要添加類似的東西:

TheConcreteTypeOf<INewsService>.Is<MyConcreteNewsService>(); 

我不知道確切的語法關閉我的頭頂,但這就是你想念。一旦你指定了它,那麼它將知道哪個INewsService實例注入到控制器中。

+0

我在註冊表中添加所有正確的映射,例如INewsService,所以它不應該是導致問題的原因。 – 2009-02-27 15:31:11

+0

我不是在實例化你的代碼。 – Micah 2009-02-27 15:32:53

0

ASP。 NET MVC目前使用默認的無參數構造函數實例化控制器,這排除了任何基於構造函數的依賴注入。爲此,您確實需要使用MvcContrib項目,該項目內置了對StructureMap(和Castle/Spring.NET/Unity)的支持,儘管當前的文檔不存在(從字面上看,您會得到一個存根維基頁面,不是一個好兆頭)。此線程中的Erv Walter代碼示例顯示瞭如何設置StructureMap集成。