1

Global.asax に依存関係を挿入しても、常に機能するとは限りません。場合によっては ContextDisposedException が発生することもあります(Page.Redirect を実行しているときに問題が発生するようです ??)。私はASP.NET WebFormコンテキストにいます。

これが私のコードです:

public class Global : HttpApplication
{
    [Inject]
    public UserManager UserManager { get; set; }

    private void Application_PostAuthenticateRequest(object sender, EventArgs e)
    {
        if (User.Identity.IsAuthenticated)
        {
            GlobalSecurityContext.SetPrincipal(User);

            string path = Request.AppRelativeCurrentExecutionFilePath;
            if (path.Contains(".aspx"))
            {
                // Get the current user
                var userData = UserManager.GetByIdWithLogin(User.Identity.Name);
                if (userData != null)
                {
                    LoginDataDTO data = userData.LoginData; 
                    if (data.XXX && ...)
                    {
                        Response.Redirect(...);
                    }
                }
            }
        }
    }

    protected void Session_End(Object sender, EventArgs e)
    {
        UserManager.Logout();
    }
}

この投稿How to inject dependencies into the global.asax.csで、Mark Seemann は、global.asax はコンポジション ルートであるため、global.asax で依存性注入を使用すべきではないと述べています。

コンストラクターにはリポジトリが必要なため、UserManager を直接呼び出したくないので、私の問題を解決する最善の方法は何ですか?

public UserManager(IGenericRepository repository) : base(repository)
{
}

そして、GenericRepositoryそれ自体が必要なコンストラクターを持っていますIContext

public GenericRepository(IContext context)
{
}

多分できるnew UserManager(new GenericRepository(new MyContext))けど

  1. リクエスト全体で同じコンテキストを再利用しません
  2. GUI で自分の AccessLayer に参照を追加する必要がありますが、これは避けたいことです。

情報として、現在、次のようにコンテキストを注入しています。

// Dynamically load the context so that we dont have a direct reference on it!
string contextType = // read type from web.config
if (!String.IsNullOrEmpty(contextType))
{
    Type context = Type.GetType(contextType);
    Bind<IContext>().To(context).InRequestScope();
}

どんな助けでも大歓迎です!

[編集]:

次のように UserProperty プロパティを変更すると、次のように機能します。

public UserManager UserManager
{
    get { return ServiceLocator.Current.GetInstance<UserManager>(); }
}
4

1 に答える 1

2

この場合、Ninject コンテナを構築し、それをこの特定のインスタンスの Service Locator として使用できます (コンポジション ルートにいるため、この時点では何も注入できません)。

于 2013-05-29T07:16:22.447 に答える