5

我想要如何配置ASP.NET MVC3的StructureMap我已經使用NuGet,我注意到它創建了一個名爲StructuremapMVC的cs文件的App_Start文件夾,所以我檢查它並注意是相同的代碼,但簡化,將手動寫上放置在Global.asax中App_Start節...首先嚐試通過NuGet的StructureMap和MVC3

這是國際奧委會類我的代碼

public static class IoC 
    { 
     public static IContainer Initialize() 
     { 
      ObjectFactory.Initialize(x => 
         { 
          x.Scan(scan => 
            { 
             scan.TheCallingAssembly(); 
             scan.WithDefaultConventions(); 
             scan.AddAllTypesOf<IController>(); 
            }); 
          x.For<OpcionDB>().Use(() => new DatabaseFactory().Get()); 
         }); 
      return ObjectFactory.Container; 
     } 
    } 

我的問題是,爲什麼我得到當我在我的控制器上注入一些IoC時(下面我使用這種模式:Entity Framework 4 CTP 4/CTP 5 Generic Repository Pattern and Unit Testable):

 private readonly IAsambleaRepository _aRep; 
     private readonly IUnitOfWork _uOw; 

     public AsambleaController(IAsambleaRepository aRep, IUnitOfWork uOw) 
     { 
      _aRep = aRep; 
      this._uOw = uOw; 
     } 

     public ActionResult List(string period) 
     { 
      var rs = _aRep.ByPeriodo(period).ToList<Asamblea>(); 

      return View(); 
     } 

異常表明:

Exception Details: System.MissingMethodException: No parameterless constructor defined for this object. 

回答

3

你得到這個錯誤,因爲你沒有設置StructureMap解決去構造所需的依賴AsambleaController所以它試圖找到一個沒有參數的構造函數。

所以你需要做的是設置StructureMap爲IAsambleaRepositoryIUnitOfWork

在附註中,我會說IUnitOfWork應該是對您的存儲庫的依賴關係,而不是您的控制器......您的控制器不需要知道工作單元。

2

如果按照上庫後,你會想這些配置增加您的IoC.cs文件:

x.For<IUnitOfWork>().HttpContextScoped().Use<UnitOfWork>(); 
x.For<IDatabaseFacroey>().HttpContextScoped().Use<DatabaseFactory>(); 
x.For<IAsambleaRepository >().HttpContextScoped().Use<AsambleaRepository>(); 

調用:scan.TheCallingAssembly();只會看MVC項目。如果你有你的服務,並在倉庫解決方案中的一個不同的項目,你將需要添加這樣的:

scan.Assembly("Your.Assembly"); 
1

在調試中運行,您可能會收到StructureMap IOC分辨率錯誤。

而不是獲得真正的解決方案錯誤,而是顯示此消息。 MVC管道的某處會吞噬真正的錯誤。

2

StructureMap.MVC3的NuGet安裝會在文件夾DependencyResolution中安裝一個名爲SmDependencyResolver.cs的文件。您會注意到那裏的GetService方法有一個try ... catch,如果發生異常,它將返回null。這可以抑制異常的細節,以便最終看到有關「無參數構造函數」的錯誤消息。

要獲取有關原始異常的更多信息,可以在該catch子句中添加一些內容以便吐出原始異常的詳細信息 - 例如Debug。WriteLine here:

public object GetService(Type serviceType) 
    { 
     if (serviceType == null) return null; 
     try 
     { 
      return serviceType.IsAbstract || serviceType.IsInterface 
        ? _container.TryGetInstance(serviceType) 
        : _container.GetInstance(serviceType); 
     } 
     catch (Exception ex) 
     { 
      Debug.WriteLine(ex.ToString()); 
      return null; 
     } 
    } 

這可以幫助您追蹤問題的根源。

+0

+1:這對我有幫助。謝謝。 – 2012-07-31 14:20:53

+0

在我使用StructureMap的所有年份中,我從來沒有注意到這一點,我想我會把這個嘗試塊取消。我認爲我不希望StructureMap不會冒泡。 – 2012-07-31 15:35:33