简体   繁体   中英

Ninject property or construction inject ASP.NET MVC3

I'm using Ninject.MVC3.

private static void RegisterServices(IKernel kernel)
{
    kernel.Bind<Repository>().To<Repository>();
}       

Registering them like so in the App_Start. It works just fine on controller that request this repository. However I also have a few classes that need this repository.

        [Inject]
        public MemberShipService(Repository repository)
        {
            this.Repository = repository;
        }

^Example from a class constructor. I've tried constructor injection this simply gives me errors because it requests an argument for the constructor. Property injection simply doesn't work.

Do I need to do something extra to make constructor or property injection work in asp.net mvc3? I haven't done any other configuration inside NinjectWebCommon other then the line I posted above.

You'll need to resolve an instance of the class using dependency resolver in order to use it, create an instance of your MemberShipService using:

var memberShipService = 
    DependencyResolver.Current.GetService(typeof(MemberShipService)) as MemberShipService;

That will bind your instance variable Repository using your constructor that you specified.

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