0

我發現http://www.devproconnections.com/content1/catpath/database-development/topic/a-perfect-storm-linq-to-sql-dependency-injection-and-asp-net-providers/page/2和有相似的代碼從網頁:有沒有更好的方法來使用Structuremap來將依賴注入到自定義RoleProvider中?

public class CustomProvider : MembershipProvider, IMembershipProvider 
{ 
    private IUserRepository _userRepo; 

    // this .ctor is used via unit tests (as a seam) 

    public CustomProvider(IUserRepository repo) 
    { 
     this._userRepo = repo; 
    } 

    // requisite parameter-less constructor: 

    public CustomProvider() 
    { 
     // do NOTHING here 
    } 

    public override bool ValidateUser(string username, string password) 
    { 
     // HACK: 
     IUserRepository repo = this._userRepo ?? ObjectFactory.GetInstance<IUserRepository>(); 
     SiteUser user = repo.GetUserByEmailAddress(username.ToLower()); 
     if (user == null) 
      return false; 

     if (!user.Active || !user.Verified) 
      return false; 

     if (user.PassPhrase.IsNullOrEmpty()) 
      return false; 

     // do other verification... etc 
    } 
} 

除了我的是一個自定義RoleProvider。調用ObjectFactory.GetInstance是一種可接受的方式將依賴關係注入到RoleProvider中?我試圖設置一個屬性來注入依賴項,但我無法讓它工作。我確定我的StructureMap註冊表是錯誤的。但在文檔過期時很難找到正確的方法。

因此,對於ASP.NET MVC3應用程序,是否在自定義RoleProvider中調用ObjectFactory?或者我應該嘗試注入物業?

如果一個屬性如何?目前我有For<RoleProvider>().Use(ctx => Roles.Provider);。但我不知道ID是Use,應該是一個Add,我也沒有把語法注入一個屬性的依賴。

仍然需要幫助 我有一個可怕的時間試圖讓miniprofiler不會拋出空裁判異常時,我只是移動StructureMap的ObjectFactory的屬性初始化。目標是允許緩存角色。我得到同樣的錯誤,因爲這些問題mini-profiler nullreferenceexceptionHelp Configure mvc mini profiler with Linq to Sql

我已更新到最新的MVCMiniProfiler,並嘗試它的MVC包。似乎在自定義RoleProvider初始化或屬性初始化之前未啓用分析。如果我從重寫的GetRolesForUser方法直接設置字段,一切都很好。如果我將該字段作爲公共屬性的支持者,我將在ProfiledDbCommand中獲得NULL異常。爲什麼?

回答

2

由於依賴於靜態和單例,Microsoft「提供程序」模式在依賴注入方面效果不佳。如果您必須使用提供程序,只需通過ObjectFactory.GetInstance執行服務位置並繼續。

+0

雅我有。奇怪地將ObjectFactory.GetInstance移動到一個屬性並檢查null,怪異MvcMiniProfiler。不知道爲什麼。但似乎它可能與事物初始化的順序有關,因爲它是一個空的異常。與StructureMap無關。 – nportelli 2012-03-18 22:37:39

相關問題