如何解决使用温莎国际奥委会在应用程序启动的用户信息库? [英] How to resolve an user repository using Windsor IoC at the start of the application?

查看:178
本文介绍了如何解决使用温莎国际奥委会在应用程序启动的用户信息库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到一个错误信息对象引用不设置到对象的实例。当我尝试使用UserRepos存储库。问题是我怎么可以在应用程序启动(ASP.NET MVC)什么是错在这里解决用户存储库?

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

感谢您对我的帮助!

推荐答案

这异常的原因是一个HttpApplication生命周期的误解。这些文章解释相当不错:

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

这篇关于如何解决使用温莎国际奥委会在应用程序启动的用户信息库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆