我有一个在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
课程中,我同时注册ApplicationSignInManager
和ApplicationUserManager
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
实例?我怎样才能让它发挥作用?
更新
我还尝试使用不同的终身经理注册我的对象,例如HierarchicalLifetimeManager
,ContainerControlledLifetimeManager
和ExternallyControlledLifetimeManager
container.RegisterType<ApplicationSignInManager>(new HierarchicalLifetimeManager());
container.RegisterType<ApplicationUserManager>(new HierarchicalLifetimeManager());