如何在ASP.Net Identity上获取OWIN上下文?

时间:2014-11-02 01:29:32

标签: asp.net-mvc entity-framework asp.net-identity-2

我试图从当前的Owin上下文中获取DbContext,因此我可以在我的应用程序中使用单个上下文,但是,我得到了NullReferenceException。

我可以访问UserManager和RoleManager:

private ApplicationUserManager _userManager;
    public ApplicationUserManager UserManager
    {
        get
        {
            return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
        }
        private set
        {
            _userManager = value;
        }
    }

他们在Identity示例项目中默认配置了它们的来源:

app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);
app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

但是试图让上下文直接使用它:

ApplicationDbContext context = HttpContext.GetOwinContext().Get<ApplicationDbContext>();

它总是在我的控制器上返回null。如何从Owin上下文中获取当前的DbContext?

修改

我正在创建一个与我的通用存储库一起使用的新上下文

public AdminController()
    {
        AppContext = new ApplicationDbContext();
        this.repoProyects = new GenericRepository<Proyect>(AppContext);
    }

但是它创建了一个问题,实体被多个上下文引用,所以我试图获得当前的Owin上下文:

public AdminController()
    {
        this.AppContext = HttpContext.GetOwinContext().Get<ApplicationDbContext>();
        this.repoProyects = new GenericRepository<Proyect>(AppContext);
    }

HttpContext在这里总是空的,所以我不知道如何让上下文传递给我的班级。