Using property injection instead of constructor injection

徘徊边缘 提交于 2019-11-30 18:15:46
lancscoder

I had a similar problem. Have a look at my questions: Using Ninject with Membership.Provider.

Basically when you initialise DepartmentsController you need to injectthis (i.e. your departments controller into your Ninject kernal. So its something like:

public class DepartmentsController : Controller
{
  private IDepartmentsRepository _departmentsRepository;

  [Inject]
  public IDepartmentsRepository DepartmentsRepository
  {
    get { return _departmentsRepository; }
    set { _departmentsRepository = value; }
  }

  public DepartmentsController()
  {
    NinjectHelper.Kernel.Inject(this);
  }
}

Where NinjectHelper in this case gets the current Ninject Kernel.

Try something like this:

Global.asax.cs

        protected void Application_Start()
        {
            DependencyResolver.SetResolver(
                new MyDependencyResolver(
                    new StandardKernel(
                        new MyModule())));
            //...
        }

MyDependencyResolver.cs

    public class MyDependencyResolver : IDependencyResolver
    {
        private IKernel kernel;

        public MyDependencyResolver(IKernel kernel)
        {
            this.kernel = kernel;
        }

        public object GetService(Type serviceType)
        {
            return kernel.TryGet(serviceType);
        }

        public IEnumerable<object> GetServices(Type serviceType)
        {
            return kernel.GetAll(serviceType);
        }
    }

MyModule.cs

    public class MyModule : NinjectModule
    {
        public override void Load()
        {
            Bind<IDepartmentsRepository>().To<DepartmentsRepository>();
        }
    }

There could be 2 reasons for object reference not set exception.

1) Ninject does not know how to Bind IDepartmentsRepository to a concrete implementation of DepartmentsRepository ( I doubt that is the case though )

2) If you are trying to access DepartmentsRepository property in your controller's constructor, it will throw the exception (since Ninject is only able to inject Property Dependencies after the object is constructed).

Hope that helps.

As Daniel T. in the above comment posted, you should check out Ninject.Web.Mvc. If you use the NinjectHttpApplication in that project, it will autowire everything for you, so that when the NinjectControllerFactory constructs a new controller, it will call Inject() for you to fill the property injections.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!