views:

68

answers:

1

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!

+4  A: 

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:

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
    }
}
Mauricio Scheffer
I should add that coding OnAuthentication in the HttpApplication isn't quite right (but that's out of the scope of this question)
Mauricio Scheffer
Thank you Mauricio for your answer! After debugging I see that OnAuthentication has been called a lot of times for each tread. For example if I use images on the page it will make a request for each image and call OnAuthentication? Am I right?Could you please explain why OnAuthentication should not be used in HttpApplication? I read some articles and I see that it is common solution to do like this. For example http://mikehadlow.blogspot.com/2008/03/forms-authentication-with-mvc-framework.html What would you advise?
podeig
@podeig: use an HttpModule or a Filter; or create another specific question on stackoverflow about this.
Mauricio Scheffer