1

セッション辞書クラスへの依存関係をコントローラーのコンストラクターに挿入しようとしています。例えば:

public AccountController(ISessionDictionary sessionDictionary)
{
    this.sessionDictionary = sessionDictionary;
}

私のglobal.asaxファイルでは:

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    RegisterGlobalFilters(GlobalFilters.Filters);
    RegisterRoutes(RouteTable.Routes);

    ModelBinders.Binders.Add(typeof(ISessionDictionary), new SessionDictionaryBinder());
}

私のSessionDictionaryBinder:

public class SessionDictionaryBinder : IModelBinder
{
    private const string sessionKey = "_seshDic";

    public object BindModel(ControllerContext controllerContext,
                            ModelBindingContext bindingContext)
    {
        if (bindingContext.Model != null)
        {
            throw new InvalidOperationException("Cannot update instances");
        }

        ISessionDictionary seshDic = (SessionDictionary)controllerContext.HttpContext.Session[sessionKey];
        if (seshDic == null)
        {
            seshDic = new SessionDictionary();
            controllerContext.HttpContext.Session[sessionKey] = seshDic;
        }

        return seshDic;
    }
}

/account/login にアクセスすると、次のエラーが表示されます。

Error activating ISessionDictionary
No matching bindings are available, and the type is not self-bindable.
Activation path:
 2) Injection of dependency ISessionDictionary into parameter sessionDictionary of constructor of     type AccountController
 1) Request for AccountController

DI に Ninject を使用していますが、App_Start ディレクトリに含まれるファイルの他のバインディングは正常に動作します。モデルバインダーがそのファイルに入るはずだと思いますが、構文は何ですか?

乾杯!

4

1 に答える 1

0

私が見ているように、あなたは物事を少し混乱させています。ここで、モデルバインダーをMVC3フレームワークに登録します。

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    RegisterGlobalFilters(GlobalFilters.Filters);
    RegisterRoutes(RouteTable.Routes);

    ModelBinders.Binders.Add(typeof(ISessionDictionary), new SessionDictionaryBinder());
}

この登録の後、ISessionDictionaryインスタンスを期待するコントローラーアクションを記述できますが、それはコントローラーコンストラクターとは関係ありません。Ninjectはバインディングを認識しないため、使用しているNinjectモジュールにバインディングを含める必要があります(ISessionDictionaryパラメーターを期待するアクションがない場合は、モデルバインダーはまったく必要ありません)。

于 2012-03-27T10:14:56.613 に答える