如何从Unity容器中解析OwinContext?

时间:2018-04-02 21:31:20

标签: c# dependency-injection asp.net-mvc-5 owin unity-container

我有一个在Asp.Net MVC 5框架顶部使用c#编写的应用程序。

我在项目中添加了Unity.Mvc包,因此我可以利用依赖注入。除非我尝试登录用户,否则一切正常。

从我的AccountController开始,我尝试使用注入的ApplicationUserManager按名称查找用户UserManager.FindByName(username)

但该行不断抛出以下错误

Cannot access a disposed object.
Object name: 'ApplicationUserManager'

我理解这里的错误,但不确定是什么导致了对象的处理。

以下是我AccountController的剥离版本,我与ApplicationUserManager对象互动。

public class AccountController : Controller
{
    protected ApplicationSignInManager SignInManager;
    protected ApplicationUserManager UserManager;
    protected IAuthenticationManager AuthenticationManager { get; set; }

    public AccountController(ApplicationUserManager userManager, ApplicationSignInManager signInManager, IAuthenticationManager authenticationManager)
    {
        UserManager = userManager;
        SignInManager = signInManager;
        AuthenticationManager = authenticationManager;
    }


    [AllowAnonymous]
    public ActionResult SignIn(string username)
    {

        var user = UserManager.FindByName(username); // this line throws an error
        if (user == null)
        {
            throw new Exception("User not found!");
        }

        SignInManager.SignIn(user, true, false);

        //...
    }
}

UnityConfig课程中,我同时注册ApplicationSignInManagerApplicationUserManager

container.RegisterType<ApplicationUser>();
container.RegisterType<DbContext, ApplicationDbContext>(new HierarchicalLifetimeManager());
container.RegisterType<ApplicationSignInManager>();
container.RegisterType<ApplicationUserManager>();
container.RegisterType<IUserStore<ApplicationUser>, UserStore<ApplicationUser>>(new HierarchicalLifetimeManager());
container.RegisterType<UserManager<ApplicationUser>>(new HierarchicalLifetimeManager());
container.RegisterType<IUserPassport, UserPassport>(new PerRequestLifetimeManager());

然后在我的Startup.Auth课程中,我有以下内容

public void ConfigureAuth(IAppBuilder app)
{
    app.CreatePerOwinContext(() => DependencyResolver.Current.GetService<ApplicationUserManager>());
    app.CreatePerOwinContext(() => DependencyResolver.Current.GetService<ApplicationSignInManager>());

    //....
}

什么可以处置ApplicationSignInManager实例?我怎样才能让它发挥作用?

更新

我还尝试使用不同的终身经理注册我的对象,例如HierarchicalLifetimeManagerContainerControlledLifetimeManagerExternallyControlledLifetimeManager

container.RegisterType<ApplicationSignInManager>(new HierarchicalLifetimeManager());
container.RegisterType<ApplicationUserManager>(new HierarchicalLifetimeManager());

0 个答案:

没有答案