Asp.net mvc 如何在应用程序启动时使用Windsor IoC解析用户存储库?

Asp.net mvc 如何在应用程序启动时使用Windsor IoC解析用户存储库?,asp.net-mvc,inversion-of-control,castle-windsor,mvccontrib,resolve,Asp.net Mvc,Inversion Of Control,Castle Windsor,Mvccontrib,Resolve,我收到一条错误消息,对象引用未设置为对象的实例。当我尝试使用UserRepos存储库时。问题是如何在应用程序ASP.NET MVC启动时解析用户存储库这里出了什么问题 public class MyApplication : HttpApplication { public IUserRepository UserRepos; public IWindsorContainer Container; protected void Application_Start()

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

谢谢你帮助我

此异常的原因是对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
    }
}

此异常的原因是对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
    }
}

我应该补充一点,在HttpApplication中对身份验证进行编码并不完全正确,但这超出了本问题的范围。谢谢毛里西奥的回答!在调试之后,我发现对每一步都调用了很多次OnAuthentication。例如,如果我在页面上使用图像,它会对每个图像发出请求并调用身份验证?我说得对吗?您能解释一下为什么在HttpApplication中不应该使用OnAuthentication吗?我读了一些文章,我发现这样做是常见的解决方案。例如,您有什么建议?@podeig:使用HttpModule或过滤器;或者在stackoverflow上创建另一个关于此的特定问题。我应该补充一点,HttpApplication中的身份验证编码不太正确,但这超出了此问题的范围谢谢Mauricio的回答!在调试之后,我发现对每一步都调用了很多次OnAuthentication。例如,如果我在页面上使用图像,它会对每个图像发出请求并调用身份验证?我说得对吗?您能解释一下为什么在HttpApplication中不应该使用OnAuthentication吗?我读了一些文章,我发现这样做是常见的解决方案。例如,您有什么建议?@podeig:使用HttpModule或过滤器;或者就此在stackoverflow上创建另一个特定问题。