开发者

How to resolve an user repository using Windsor IoC at the start of the application?

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!


The cause of this exception is a misunderstanding of the HttpApplication lifecycle. These articles explain it quite well:

  • http://ayende.com/Blog/archive/2006/09/10/SolvingTheHttpModuleMess.aspx
  • http://blog.andreloker.de/post/2008/05/HttpApplication-instances.aspx

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
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜