如何在应用程序启动时使用 Windsor IoC 解析用户存储库?
我收到一条错误消息“对象引用未设置到对象的实例。”当我尝试使用 UserRepos 存储库时。问题是如何在应用程序启动时解析用户存储库(ASP.NET MVC)这里出了什么问题?
public class MyApplication : HttpApplication
{
public IUserRepository UserRepos;
public IWindsorContainer Container;
protected void Application_Start()
{
Container = new WindsorContainer();
// Application services
Container.Register(
Component.For<IUserRepository>().ImplementedBy<UserRepository>()
);
UserRepos = Container.Resolve<IUserRepository>();
}
private void OnAuthentication(object sender, EventArgs e)
{
if (Context.User != null)
{
if (Context.User.Identity.IsAuthenticated)
{
//Error here "Object reference not set to an instance of an object."
var user = UserRepos.GetUserByName(Context.User.Identity.Name);
var principal = new MyPrincipal(user);
Thread.CurrentPrincipal = Context.User = principal;
return;
}
}
}
}
谢谢你帮助我!
I get an error message "Object reference not set to an instance of an object." when I try to use an UserRepos repository. Question is how can I resolve user repository at the start of the application (ASP.NET MVC) What is wrong here?
public class MyApplication : HttpApplication
{
public IUserRepository UserRepos;
public IWindsorContainer Container;
protected void Application_Start()
{
Container = new WindsorContainer();
// Application services
Container.Register(
Component.For<IUserRepository>().ImplementedBy<UserRepository>()
);
UserRepos = Container.Resolve<IUserRepository>();
}
private void OnAuthentication(object sender, EventArgs e)
{
if (Context.User != null)
{
if (Context.User.Identity.IsAuthenticated)
{
//Error here "Object reference not set to an instance of an object."
var user = UserRepos.GetUserByName(Context.User.Identity.Name);
var principal = new MyPrincipal(user);
Thread.CurrentPrincipal = Context.User = principal;
return;
}
}
}
}
Thank you for helping me!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
导致此异常的原因是对 HttpApplication 生命周期的误解。这些文章很好地解释了这一点:
在您的情况下,这将是正确的容器用法:
The cause of this exception is a misunderstanding of the HttpApplication lifecycle. These articles explain it quite well:
in your case, this would be the correct container usage: