大约一年前,在 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 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
属性)演示了一个示例服务定位器作为反模式 http://blog.ploeh.dk/2010/02/03/ServiceLocatorisanAnti-Pattern/。所以我更喜欢删除所有这些东西并遵循 DI 原则。这篇博文 http://tech.trailmax.info/2014/09/aspnet-identity-and-ioc-container-registration/展示了如何重构默认项目模板以遵循这些原则。
我希望依赖注入能够在 ASP.NET 的下一个版本中得到改进。他们其实promised http://www.hanselman.com/blog/IntroducingASPNETVNext.aspx支持开箱即用的依赖注入。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)