2014-11-23 95 views
4

大約一年前,在Visual Studio中創建時自動生成的MVC項目沒有包含OWIN。作爲再次提出申請的人,想要了解這些變化,我想知道OWIN是否可以取代我的DI。OWIN可以在ASP.NET MVC應用程序中替換DI嗎?

據我所知,Startup.Auth.cs中的這一點是集中創建用戶管理器(處理身份)以及爲應用程序創建數據庫連接。

public partial class Startup 
{ 
    // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864 
    public void ConfigureAuth(IAppBuilder app) 
    { 
     // Configure the db context and user manager to use a single instance per request 
     app.CreatePerOwinContext(ApplicationDbContext.Create); 
     app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create); 

     // Other things... 
    } 
} 

從一個非常有用的資料來源:http://blogs.msdn.com/b/webdev/archive/2014/02/12/per-request-lifetime-management-for-usermanager-class-in-asp-net-identity.aspx,它看起來好像我們可以用代碼在任何時間訪問用戶管理器或的DbContext像下面

public class AccountController : Controller 
{ 
    private ApplicationUserManager _userManager; 

    public AccountController() { } 

    public AccountController(ApplicationUserManager userManager) 
    { 
     UserManager = userManager; 
    } 

    public ApplicationUserManager UserManager { 
     get 
     { 
      // HttpContext.GetOwinContext().Get<ApplicationDbContext>(); // The ApplicationDbContextis retrieved like so 
      return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();     
     } 
     private set 
     { 
      _userManager = value; 
     } 
    } 

    // Other things... 
} 

如果我沒有理解錯的一切,所有的我可以做從使用StructureMap到OWIN(處理DI)的操作,只是像上面的AccountController一樣構造我的控制器。有什麼我失蹤或我仍然需要DI在我的應用程序/是否OWIN給我DI?

回答

6

我個人不喜歡使用OWIN解決依賴關係的想法。

默認實現AccountController.UserManager(以及其他AccountManager屬性)演示了service locator as an anti-pattern的示例。所以我寧願刪除所有這些東西,並遵循DI原則。 This blog post顯示瞭如何重構默認項目模板以遵循這些原則。

我希望在ASP.NET的下一個版本中依賴注入會得到改進。它們實際上是promised支持依賴注入開箱即用。

+0

偉大的鏈接,感謝您找到該博客文章! – Zac 2014-11-23 22:32:26

相關問題