Ninject constructor injection in WPF

后端 未结 1 1959
走了就别回头了
走了就别回头了 2020-12-14 04:25

Is it possible to use ninject for dependency injection in such a way that the result would be something like the injection I can get in MVC. To elaborate, if I use the MVC n

相关标签:
1条回答
  • 2020-12-14 04:34

    Based on the comments & your confusion, it looks like MVVM is a good match for you. The challenge is, LEARNING MVVM.

    So crack open a good link and get rolling. MVVM is surprisingly easy to do, and it's pretty easy to wrap it all up with Ninject and put a bow on it.

    The initial learning curve if you DON'T use a 3rd party library for Ninject + MVVM like I did, is a bit steep. So here's a couple of things I had to understand:

            DataContext="{Binding Path=ResultViewModel,Source={StaticResource ServiceLocator}}"
    

    This little addition makes allows you to trigger ninject to get your viewmodel information from your XAML:

    <Application.Resources>
        <ioc:NinjectServiceLocator x:Key="ServiceLocator" />
    </Application.Resources>
    

    this little trick allows you to assign that staticresource from your app.xaml file to the relevant class

    public class NinjectServiceLocator
    {
        private readonly IKernel kernel;
    
        public NinjectServiceLocator()
        {
            kernel = new StandardKernel(new MyMvvmModule());
        }
    
        public ResultViewModel ResultViewModel
        {
            get { return kernel.Get<ResultViewModel>(); }
        }
    }
    

    This is notable. Every viewmodel must be listed as a property in the ServiceLocator in order for Ninject to generate them. Finally, MyMvvmModule in the example above is the standard Ninject class where you stick your override for Load() and bind all your interfaces.

    0 讨论(0)
提交回复
热议问题