简体   繁体   中英

Accessing a repository in AccountController through constructor

I am using the MVC AccountController that implements the ASP.NET Membership Provder. I have a repository with all my database access in which I have added a Countries property that returns a list of countries. I want to add a country dropdown to the Register page so I need to be able to get this data from my repository and pass it to the View. I have been using contructor injection in my other controllers but I dont know how to apply this to the existing 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();
    } 

Can I change the existing AccountController constructor to access my repository?

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

If you have already registered your repository with ninject, you should be able to just add a third parameter to the constructor of the controller. I saw your earlier comment about ninject, but I'm not using NinjectModule. If you're using MVC 3, would suggest that you take a look at nuget (http://nuget.codeplex.com) and download the Ninject.MVC3 packge which adds a AppStartNinjectMvc3 class to your project where you can register services with the kernel.Bind methods:

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

Hope this helps.

If your using MVC2 you should take a look at http://mvcstarter.codeplex.com/ it's also using Ninject. Like @Johan said you simply have to put the parameter and bind it in the global.asax.cs.

Hope it helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM