0

我有一个模型活页夹如下

public PartyRoleModelBinder(IPartyRoleFactory prFactory)
    {
        PrFactory = prFactory;
        PRepo = pRepo;
        PrtRepo = prtRepo;
    }
protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
    {
       //doing some work here
    }

    private IPartyRoleFactory PrFactory { get; set; }
    private IPartyRepository PRepo { get; set; }
    private IPartyRoleTypeRepository PrtRepo { get; set; }

我在 global.asax.cs 中注册如下:

ModelBinders.Binders.Add(typeof(PartyRole), new PartyRoleModelBinder(DependencyResolver.Current.GetService<IPartyRoleFactory>()));

到这里为止一切都很好。现在我的问题是我必须对我的构造函数有更多依赖,例如:

public PartyRoleModelBinder(IPartyRoleFactory prFactory, IPartyRoleTypeRepository prtRepo, IPartyRepository pRepo)
    {
        PrFactory = prFactory;
        PRepo = pRepo;
        PrtRepo = prtRepo;
    }

但我确定如何在 global.asax.cs 中注册它

如果我像下面这样使用

ModelBinders.Binders.Add(typeof(PartyRole), new PartyRoleModelBinder(DependencyResolver.Current.GetService<IPartyRoleFactory>()));

它抛出:错误 25 'PartyWeb.ModelBinders.PartyRoleModelBinder' 不包含带有 1 个参数的构造函数 C:\d2\Apps\d2admin\Global.asax.cs 35 57 d2admin

或者

ModelBinders.Binders.Add(typeof(PartyRole), new PartyRoleModelBinder(DependencyResolver.Current.GetService<IPartyRoleFactory, IPartyRepository, IPartyRoleTypeRepository>()));

编译错误:错误 25 非泛型方法 'System.Web.Mvc.IDependencyResolver.GetService(System.Type)' 不能与类型参数一起使用 C:\d2\Apps\d2admin\Global.asax.cs 35 109 d2admin

有人可以建议我该如何解决吗?

4

2 回答 2

3

您正在尝试在其(修改后的)构造函数中创建一个PartyRoleModelBinder需要3 个参数的新实例,但您只传递了 1 个参数并且DependencyResolver.Current.GetService在此过程中使用不正确。

尝试:

 var resolver = DependencyResolver.Current;
 IPartyRoleFactory roleFactory = resolver.GetService<IPartyRoleFactory>();
 IPartyRepository repo = resolver.GetService<IPartyRepository>();
 IPartyRoleTypeRepo typeRepo = resolver.GetService<IPartyRoleTypeRepository>();

 var partyRoleModelBinder = new PartyRoleModelBinder(roleFactory, typeRepo, repo);

 ModelBinders.Binders.Add(typeof(PartyRole), partyRoleModelBinder);
于 2013-07-03T11:52:42.490 回答
0

我同意haim770。另一种方法是:

    ModelBinders.Binders.Add(typeof(PartyRole), new PartyRoleModelBinder(DependencyResolver.Current.GetService<IPartyRoleFactory>(),
                    DependencyResolver.Current.GetService<IPartyRoleTypeRepository>(), DependencyResolver.Current.GetService<IPartyRepository>()));
于 2013-07-04T03:58:23.913 回答