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 に答える