How to Use Ninject with MVVM Light

I am trying to replace SimpleIoc with Ninject 3 in a WP7 application. So far I have Portable.CommonServiceLocator.NinjectAdapter in my app and it contains a service locator but everytime I try to use, my app crashes so I must be missing something.

Simple Ioc way

using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Ioc;
using Microsoft.Practices.ServiceLocation;
using MvvmLight1.Model;

namespace MvvmLight1.ViewModel
{
    public class ViewModelLocator
    {
        static ViewModelLocator()
        {
            ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);

            if (ViewModelBase.IsInDesignModeStatic)
            {
                SimpleIoc.Default.Register<IDataService, Design.DesignDataService>();
            }
            else
            {
                SimpleIoc.Default.Register<IDataService, DataService>();
            }

            SimpleIoc.Default.Register<MainViewModel>();
        }

        /// <summary>
        /// Gets the Main property.
        /// </summary>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance",
            "CA1822:MarkMembersAsStatic",
            Justification = "This non-static member is needed for data binding purposes.")]
        public MainViewModel Main
        {
            get
            {
                return ServiceLocator.Current.GetInstance<MainViewModel>();
            }
        }
    }

Ninject

using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Ioc;
using Microsoft.Practices.ServiceLocation;
using MvvmLight1.Model;
using CommonServiceLocator.NinjectAdapter;

namespace MvvmLight1.ViewModel
{
    public class ViewModelLocator
    {
        static ViewModelLocator()
        {
            Ninject.StandardKernel k = new Ninject.StandardKernel();
            ServiceLocator.SetLocatorProvider(() => new NinjectServiceLocator(k));
            k.Bind<IDataService, Design.DesignDataService>();
            k.Bind<MainViewModel>().ToSelf();

        }

        /// <summary>
        /// Gets the Main property.
        /// </summary>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance",
            "CA1822:MarkMembersAsStatic",
            Justification = "This non-static member is needed for data binding purposes.")]
        public MainViewModel Main
        {
            get
            {
                return ServiceLocator.Current.GetInstance<MainViewModel>();
            }
        }
    }
}

Crashes

  [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance",
        "CA1822:MarkMembersAsStatic",
        Justification = "This non-static member is needed for data binding purposes.")]
    public MainViewModel MainVm
    {
        get
        {
            return ServiceLocator.Current.GetInstance<MainViewModel>();
        }
    }


Microsoft.Practices.ServiceLocation.ActivationException was unhandled
  Message=Activation error occured while trying to get instance of type MainViewModel, key ""
  StackTrace:
       at Microsoft.Practices.ServiceLocation.ServiceLocatorImplBase.GetInstance(Type serviceType, String key)
       at Microsoft.Practices.ServiceLocation.ServiceLocatorImplBase.GetInstance[TService]()
       at PriceCheck.WindowsMobile.ViewModel.ViewModelLocator.get_MainVm()
       at PriceCheck.WindowsMobile.Views.MainPage..ctor()
       at System.Reflection.RuntimeConstructorInfo.InternalInvoke(RuntimeConstructorInfo rtci, BindingFlags invokeAttr, Binder binder, Object parameters, CultureInfo culture, Boolean isBinderDefault, Assembly caller, Boolean verifyAccess, StackCrawlMark& stackMark)
       at System.Reflection.RuntimeConstructorInfo.InternalInvoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, StackCrawlMark& stackMark)
       at System.Activator.InternalCreateInstance(Type type, Boolean nonPublic, StackCrawlMark& stackMark)
       at System.Activator.CreateInstance(Type type)
       at System.Windows.Navigation.PageResourceContentLoader.BeginLoad_OnUIThread(AsyncCallback userCallback, PageResourceContentLoaderAsyncResult result)
       at System.Windows.Navigation.PageResourceContentLoader.<>c__DisplayClass4.<BeginLoad>b__0(Object args)
       at System.Reflection.RuntimeMethodInfo.InternalInvoke(RuntimeMethodInfo rtmi, Object obj, BindingFlags invokeAttr, Binder binder, Object parameters, CultureInfo culture, Boolean isBinderDefault, Assembly caller, Boolean verifyAccess, StackCrawlMark& stackMark)
       at System.Reflection.RuntimeMethodInfo.InternalInvoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, StackCrawlMark& stackMark)
       at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)
       at System.Delegate.DynamicInvokeOne(Object[] args)
       at System.MulticastDelegate.DynamicInvokeImpl(Object[] args)
       at System.Delegate.DynamicInvoke(Object[] args)
       at System.Windows.Threading.DispatcherOperation.Invoke()
       at System.Windows.Threading.Dispatcher.Dispatch(DispatcherPriority priority)
       at System.Windows.Threading.Dispatcher.OnInvoke(Object context)
       at System.Windows.Hosting.CallbackCookie.Invoke(Object[] args)
       at System.Windows.Hosting.DelegateWrapper.InternalInvoke(Object[] args)
       at System.Windows.RuntimeHost.ManagedHost.InvokeDelegate(IntPtr pHandle, Int32 nParamCount, ScriptParam[] pParams, ScriptParam& pResult)
  InnerException: System.TypeLoadException
       Message=Could not load type 'Ninject.Infrastructure.ReferenceEqualWeakReference' from assembly 'Ninject.Common, Version=3.0.0.0, Culture=neutral, PublicKeyToken=C7192DC5380945E7'.
       StackTrace:
            at Ninject.Activation.Strategies.ActivationCacheStrategy.Activate(IContext context, InstanceReference reference)
            at Ninject.Activation.Pipeline.<>c__DisplayClass2.<Activate>b__0(IActivationStrategy s)
            at Ninject.Infrastructure.Language.ExtensionsForIEnumerableOfT.Map[T](IEnumerable`1 series, Action`1 action)
            at Ninject.Activation.Pipeline.Activate(IContext context, InstanceReference reference)
            at Ninject.Activation.Context.Resolve()
            at Ninject.KernelBase.<>c__DisplayClass13.<Resolve>b__d(IBinding binding)
            at System.Linq.Enumerable.<SelectIterator>d__d`2.MoveNext()
            at System.Linq.Enumerable.Single[TSource](IEnumerable`1 source)
            at Ninject.ResolutionExtensions.Get(IResolutionRoot root, Type service, IParameter[] parameters)
            at CommonServiceLocator.NinjectAdapter.NinjectServiceLocator.DoGetInstance(Type serviceType, String key)
            at Microsoft.Practices.ServiceLocation.ServiceLocatorImplBase.GetInstance(Type serviceType, String key)
            at Microsoft.Practices.ServiceLocation.ServiceLocatorImplBase.GetInstance[TService]()
            at PriceCheck.WindowsMobile.ViewModel.ViewModelLocator.get_MainVm()
            at PriceCheck.WindowsMobile.Views.MainPage..ctor()
            at System.Reflection.RuntimeConstructorInfo.InternalInvoke(RuntimeConstructorInfo rtci, BindingFlags invokeAttr, Binder binder, Object parameters, CultureInfo culture, Boolean isBinderDefault, Assembly caller, Boolean verifyAccess, StackCrawlMark& stackMark)
            at System.Reflection.RuntimeConstructorInfo.InternalInvoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, StackCrawlMark& stackMark)
            at System.Activator.InternalCreateInstance(Type type, Boolean nonPublic, StackCrawlMark& stackMark)
            at System.Activator.CreateInstance(Type type)
            at System.Windows.Navigation.PageResourceContentLoader.BeginLoad_OnUIThread(AsyncCallback userCallback, PageResourceContentLoaderAsyncResult result)
            at System.Windows.Navigation.PageResourceContentLoader.<>c__DisplayClass4.<BeginLoad>b__0(Object args)
            at System.Reflection.RuntimeMethodInfo.InternalInvoke(RuntimeMethodInfo rtmi, Object obj, BindingFlags invokeAttr, Binder binder, Object parameters, CultureInfo culture, Boolean isBinderDefault, Assembly caller, Boolean verifyAccess, StackCrawlMark& stackMark)
            at System.Reflection.RuntimeMethodInfo.InternalInvoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, StackCrawlMark& stackMark)
            at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)
            at System.Delegate.DynamicInvokeOne(Object[] args)
            at System.MulticastDelegate.DynamicInvokeImpl(Object[] args)
            at System.Delegate.DynamicInvoke(Object[] args)
            at System.Windows.Threading.DispatcherOperation.Invoke()
            at System.Windows.Threading.Dispatcher.Dispatch(DispatcherPriority priority)
            at System.Windows.Threading.Dispatcher.OnInvoke(Object context)
            at System.Windows.Hosting.CallbackCookie.Invoke(Object[] args)
            at System.Windows.Hosting.DelegateWrapper.InternalInvoke(Object[] args)
            at System.Windows.RuntimeHost.ManagedHost.InvokeDelegate(IntPtr pHandle, Int32 nParamCount, ScriptParam[] pParams, ScriptParam& pResult)

Edit

I also tried to do this

 IKernel k = new StandardKernel();
 k.Bind<IDataService, Design.DesignDataService>();
 ServiceLocator.SetLocatorProvider(() => new NinjectServiceLocator(k));
    var d = k.Get<IDataService>();

Which gives me a NULL exception when the "Get" tries to happen.

An unhandled exception of type 'System.NullReferenceException' occurred in Ninject.Common.dll


System.NullReferenceException was unhandled
  Message=NullReferenceException
  StackTrace:
       at Ninject.Planning.Bindings.BindingConfiguration.GetProvider(IContext context)
       at Ninject.Planning.Bindings.Binding.GetProvider(IContext context)
       at Ninject.Activation.Context.GetProvider()
       at Ninject.Activation.Context.Resolve()
       at Ninject.KernelBase.<>c__DisplayClass13.<Resolve>b__d(IBinding binding)
       at System.Linq.Enumerable.<SelectIterator>d__d`2.MoveNext()
       at System.Linq.Enumerable.<CastIterator>d__b0`1.MoveNext()
       at System.Linq.Enumerable.Single[TSource](IEnumerable`1 source)
       at Ninject.ResolutionExtensions.Get[T](IResolutionRoot root, IParameter[] parameters)
       at MvvmLight2.ViewModel.ViewModelLocator..cctor()
       at System.Reflection.RuntimeConstructorInfo.InternalInvoke(RuntimeConstructorInfo rtci, BindingFlags invokeAttr, Binder binder, Object parameters, CultureInfo culture, Boolean isBinderDefault, Assembly caller, Boolean verifyAccess, StackCrawlMark& stackMark)
       at System.Reflection.RuntimeConstructorInfo.InternalInvoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, StackCrawlMark& stackMark)
       at System.Reflection.ConstructorInfo.Invoke(Object[] parameters)
       at MS.Internal.TypeProxy.<>c__DisplayClass30.<GetCreateObjectDelegate>b__2a()
       at MS.Internal.TypeProxy.CreateInstance(UInt32 customTypeId)
       at MS.Internal.XamlManagedRuntimeRPInvokes.CreateInstance(XamlTypeToken inXamlType, XamlQualifiedObject& newObject)
       at MS.Internal.XcpImports.Application_LoadComponentNative(IntPtr pContext, IntPtr pComponent, UInt32 cUriStringLength, String uriString, UInt32 cXamlStrLength, Byte* pXamlStr, UInt32 cAssemblyStrLength, String assemblyStr)
       at MS.Internal.XcpImports.Application_LoadComponent(IManagedPeerBase componentAsDO, String resourceLocator, UnmanagedMemoryStream stream, UInt32 numBytesToRead, String assemblyString)
       at System.Windows.Application.LoadComponent(Object component, Uri resourceLocator)
       at MvvmLight2.App.InitializeComponent()
       at MvvmLight2.App..ctor()
       at System.Reflection.RuntimeConstructorInfo.InternalInvoke(RuntimeConstructorInfo rtci, BindingFlags invokeAttr, Binder binder, Object parameters, CultureInfo culture, Boolean isBinderDefault, Assembly caller, Boolean verifyAccess, StackCrawlMark& stackMark)
       at System.Reflection.RuntimeConstructorInfo.InternalInvoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, StackCrawlMark& stackMark)
       at System.Reflection.ConstructorInfo.Invoke(Object[] parameters)
       at MS.Internal.TypeProxy.<>c__DisplayClass30.<GetCreateObjectDelegate>b__2a()
       at MS.Internal.TypeProxy.CreateInstance(UInt32 customTypeId)
       at MS.Internal.FrameworkCallbacks.CreateKnownObject(IntPtr nativeRootPeer, UInt32 customTypeId, String initializationString, IntPtr& nativePeer, UInt32 isCreatedByParser)
       at MS.Internal.FrameworkCallbacks.CreateUnknownObject(String assemblyName, String typeName, IntPtr nativeRootPeer, String initializationString, UInt32& customTypeId, UInt32& coreTypeId, UInt32& typeFlags, IntPtr& nativePeer)

Edit 3

For some reason I remade the my sample application and the "Get" method does not seem to be there. Not sure if I am missing some import or something.

Original problem still exists.

Answers


I just ran into this issue myself. What I ended up discovering is that this was a bug introduced in version 3.0.7 of the Portable.Ninject NuGet package. In my case, reverting to the 3.0.6 version of the Portable.Ninject package fixed the issue. The issue only affects Windows Phone 7. The exact same binary runs on Windows Phone 8 without issues.

http://www.nuget.org/packages/Portable.Ninject/3.0.6


Need Your Help

Custom Exceptions in PCL files

c# xamarin monotouch monodroid portable-class-library

I'm currently converting our .net business objects library to a PCL file so that it can be used with Xamarin IOS/Android and while it contains mainly POCO objects, it also contains custom exception...

Try/Catch not working inside a custom class, NPE

android nullpointerexception try-catch

Fairly simple. I have a BIG class for my main project, and it became "unwieldy". SO today I decided to try making my own class, so I could simplify some of the code in the big class.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.