【发布时间】:2014-11-23 03:19:25
【问题描述】:
大约一年前,在 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?
【问题讨论】:
标签: c# asp.net asp.net-mvc entity-framework owin