2011-03-04 52 views
0

我正在使用实现ASP.NET MembershipProvider的MVC AccountController。 我有一个所有数据库访问的存储库,其中我添加了一个返回国家/地区列表的国家/地区属性。我想将国家下拉列表添加到注册页面,因此我需要能够从我的存储库获取这些数据并将其传递给View。 我一直在我的其他控制器中使用构造器注入,但我不知道如何将其应用于现有的AccountController。通过构造函数访问AccountController中的存储库

 // This constructor is used by the MVC framework to instantiate the controller using 
    // the default forms authentication and membership providers. 

    public AccountController() 
     : this(null, null) 
    { 
    } 

    // This constructor is not used by the MVC framework but is instead provided for ease 
    // of unit testing this type. See the comments at the end of this file for more 
    // information. 
    public AccountController(IFormsAuthentication formsAuth, IMembershipService service) 
    { 
     FormsAuth = formsAuth ?? new FormsAuthenticationService(); 
     MembershipService = service ?? new AccountMembershipService(); 
    } 

我可以更改现有的AccountController构造函数来访问我的存储库吗?

回答

0

如果您已经使用ninject注册了您的存储库,那么您应该能够向控制器的构造函数中添加第三个参数。我看到您之前对ninject的评论,但我没有使用NinjectModule。如果您使用的是MVC 3,建议您查看nuget(http://nuget.codeplex.com)并下载Ninject.MVC3 packge,它将AppStartNinjectMvc3类添加到您的项目,您可以在其中使用内核注册服务。绑定方法:

kernel.Bind<IThingRepository>().To<SqlThingRepository>(); 

希望这会有所帮助。

+0

我可以推荐使用Windsor,因为它很好地实现了*组件负担*。 – Henrik 2011-03-05 19:19:23

1

在您的IoC引擎中注册服务,然后删除默认构造函数。

+0

我得到它通过添加一个引用作为第三个参数int defautl构造函数,但是这是否会打败IoC的目的?我正在使用NInject,因此我会将它添加到NinjectModule'私人类PublicationServices:NinjectModule { } {0} {0} {0} public override void Load() { ??这里有什么? } }' – Brendan 2011-03-04 17:11:38

+0

我想你已经有了你的答案。但要澄清;默认c'tor是不包含任何参数的。你不做“?? new XXX();”如果您正在使用IoC,因为这会破坏IoC的目的,您自己并不会“新增”自己的事情。 – Henrik 2011-03-05 19:25:49

+0

感谢Henrik,我还没有正确设置我的绑定,但我现在已经开始了IoC的悬挂。 – Brendan 2011-03-07 00:25:24

0

如果你使用MVC2你应该看看http://mvcstarter.codeplex.com/它也使用Ninject。就像@Johan所说的,你只需要放入参数并将其绑定到global.asax.cs即可。

希望它有帮助!

+0

感谢温尼,这是一个很好的例子。 – Brendan 2011-03-05 13:32:41