1

我收到一条错误消息“对象引用未设置为对象的实例。” 当我尝试使用 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;
            }
        }
    }
}

感谢你们对我的帮助!

4

1 回答 1

4

这个异常的原因是对 HttpApplication 生命周期的误解。这些文章很好地解释了它:

在您的情况下,这将是正确的容器用法:

public class MyApplication: HttpApplication {
    private static IWindsorContainer container;

    protected void Application_Start()     {
            container = new WindsorContainer();
            ... registrations
    }

    private void OnAuthentication(object sender, EventArgs e) {
        var userRepo = container.Resolve<IUserRepository>();
        ... code that uses userRepo
    }
}
于 2010-07-28T19:04:22.720 回答