1

一言で言えば、私の質問はこれに要約されます:

コンテナー/サービス ロケーターからモデルを解決するカスタム モデル バインダーを MVC4 に実装する必要があります。次のモデル バインダーを実装しました。

public class ServiceLocatorModelBinder : DefaultModelBinder
{
    private readonly IServiceLocator _serviceLocator;

    public ServiceLocatorModelBinder(IServiceLocator serviceLocator)
    {
        _serviceLocator = serviceLocator;
    }

    protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
    {
        var typeValue = bindingContext.ValueProvider.GetValue(bindingContext.ModelName + ".ModelType");
        var type = Type.GetType(
            (string)typeValue.ConvertTo(typeof(string)),
            true
        );
        var model = _serviceLocator.GetInstance(modelType);
        bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, type);
        return model;
    }
}

そして今、mvc の DefaultModelBinder の代わりにこれを使用して、すべてのモデルを解決したいと考えています。どうすればいいですか?

これを行う必要性を明確にするために(一般的には、ビューモデル/モデルに具体的な単純なクラスを使用することがベストプラクティスと見なされているため)、単純なビューモデルの代わりにプロキシを自動的に生成するという概念を試しています。アプリケーション全体で /poco クラスを使用しているため、バインドする具体的な型がありません。私が達成したい目標は、モデル/ビュー モデルをシンプルに保つパターンを採用し、これらのクラスに誰もロジックをまったく追加できないようにすることで、それをさらに 1 歩強化することです。ここで、モデル タイプを解決するためのコンテナーが必要になります。

4

1 に答える 1

3

どうすればいいですか?

デフォルトのモデル バインダーを次のカスタム バインダーに置き換えることができますApplication_Start

IServiceLocator sl = ...
ModelBinders.Binders.DefaultBinder = new ServiceLocatorModelBinder(sl);
于 2012-08-19T12:58:01.023 に答える