开发者

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)
    开发者_如何学Go{
    }

    // 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?


Register the services in your IoC engine and then remove the default constructor.


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!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜