[英]Can OWIN replace DI in a ASP.NET MVC application?
大約一年前,在Visual Studio中創建時自動生成的MVC項目不包含任何關於OWIN的內容。 作為再次申請的人,試圖了解變化,我想知道OWIN是否可以取代我的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嗎?
我個人不喜歡使用OWIN解決依賴關系的想法。
AccountController.UserManager
的默認實現(以及一些其他AccountManager
屬性)演示了服務定位器作為反模式的示例。 所以我更喜歡刪除所有內容並遵循DI原則。 此博客文章顯示了如何重構默認項目模板以遵循這些原則。
我希望在下一版本的ASP.NET中改進依賴注入。 他們實際上承諾支持開箱即用的依賴注入。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.