1

I am just getting started with Ninject (3.2.2.0) for DI for my MVVM project. My implementation is very simple so far - no interfaces being used with Ninject, only doing DI for the ViewModel. I am getting a NullReferenceException when the XAML for the MainWindow is being processed. The constructor for the View & ViewModel are successfully completed before the NRE. The exception occurs after App.OnStartup() completes. Here is App.xaml.cs:

namespace PSS
{
    public partial class App : Application
    {
        private IKernel Container;

        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);
            Container = new StandardKernel();
            Application.Current.MainWindow = Container.Get<MainWindow>();
            Application.Current.MainWindow.Show();
        }
    }
}

and here is MainWindow.xaml.cs:

namespace PSS
{
    public partial class MainWindow : Window
    {
        public MainWindow(MainWindowVM viewModel)
        {
            DataContext = viewModel;
            InitializeComponent();
            Messenger.Default.Register<string>(this, UICommands);
            CMTextBox.Focus();
        }
    }
}

Any suggestions as to why something in the XAML is apparently not getting initialized? I do have a couple IValueConverters being used in the XAML, but when I remove their references, the NRE still happens.

EDIT: Stacktrace of the NRE:

System.NullReferenceException was unhandled
  _HResult=-2147467261
  _message=Object reference not set to an instance of an object.
  HResult=-2147467261
  IsTransient=false
  Message=Object reference not set to an instance of an object.
  Source=mscorlib
  StackTrace:
   at System.DefaultBinder.BindToMethod(BindingFlags bindingAttr, MethodBase[] match, Object[]& args, ParameterModifier[] modifiers, CultureInfo cultureInfo, String[] names, Object& state)
   at MS.Internal.Xaml.Runtime.DynamicMethodRuntime.CreateInstanceWithCtor(Type type, Object[] args)
   at MS.Internal.Xaml.Runtime.ClrObjectRuntime.CreateInstance(XamlType xamlType, Object[] args)
   at System.Xaml.XamlObjectWriter.Logic_CreateAndAssignToParentStart(ObjectWriterContext ctx)
   at System.Xaml.XamlObjectWriter.WriteStartMember(XamlMember property)
   at System.Windows.Markup.WpfXamlLoader.TransformNodes(XamlReader xamlReader, XamlObjectWriter xamlWriter, Boolean onlyLoadOneNode, Boolean skipJournaledProperties, Boolean shouldPassLineNumberInfo, IXamlLineInfo xamlLineInfo, IXamlLineInfoConsumer xamlLineInfoConsumer, XamlContextStack`1 stack, IStyleConnector styleConnector)
   at System.Windows.Markup.WpfXamlLoader.Load(XamlReader xamlReader, IXamlObjectWriterFactory writerFactory, Boolean skipJournaledProperties, Object rootObject, XamlObjectWriterSettings settings, Uri baseUri)
   at System.Windows.Markup.WpfXamlLoader.LoadBaml(XamlReader xamlReader, Boolean skipJournaledProperties, Object rootObject, XamlAccessLevel accessLevel, Uri baseUri)
   at System.Windows.Markup.XamlReader.LoadBaml(Stream stream, ParserContext parserContext, Object parent, Boolean closeStream)
   at System.Windows.Application.LoadBamlStreamWithSyncInfo(Stream stream, ParserContext pc)
   at System.Windows.Application.DoStartup()
   at System.Windows.Application.<.ctor>b__1_0(Object unused)
   at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
   at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
   at System.Windows.Threading.DispatcherOperation.InvokeImpl()
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Windows.Threading.DispatcherOperation.Invoke()
   at System.Windows.Threading.Dispatcher.ProcessQueue()
   at System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
   at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
   at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
   at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
   at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
   at System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
   at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
   at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
   at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
   at System.Windows.Application.RunDispatcher(Object ignore)
   at System.Windows.Application.RunInternal(Window window)
   at PSS.App.Main() in c:\Users\conrad\VSSolutions\Measurements\PSS\obj\Debug\App.g.cs:line 0
   at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
   at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
   at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ThreadHelper.ThreadStart()
Conrad
  • 2,197
  • 28
  • 53
  • 1
    Where's the exception details? Debug, when the exception dialog pops up click the link at the bottom that says "copy exception details to the clipboard" and paste them into an [edit]. Warning: if you take a screenshot of the dialog and paste *that*, I'll dupehammer this with the power of a thousand suns. –  Feb 09 '16 at 16:54
  • @Will stacktrace added – Conrad Feb 09 '16 at 17:01
  • Hmm, that's a squirly one. I'd wager you have SOMETHING that's being spun up that is throwing an exception in the constructor. So what I'd do is for *anything* referenced in XAML, and *anything those things reference*, I'd examine each of their constructors in detail (just your code, mind you). That's usually enough to detect places where NREs may happen and not be handled properly. If you can't figure it out, place a breakpoint in each and every ctor and walk through it during loading. –  Feb 09 '16 at 17:08
  • FYI, you can configure vs to break on any NRE. See this answer http://stackoverflow.com/a/21737654/1228 –  Feb 09 '16 at 17:14
  • @Will well I literally just commented everything out of my .xaml file except for an empty ``Grid`` and I still get the same error. I will keep hunting. Also, breaking on any NRE didn't provide any more hints. – Conrad Feb 09 '16 at 18:54
  • So an empty project throws an NRE? Something is seriously botched here. Restart VS. Clean. Manually clean everything from explorer. Create a new, empty project and see if it repros. If so, go open a connect with MS. That's not right. You can try reinstalling visual studio if that's where you're at. If not, then start adding stuff into the new project until you repro. Sucks, but that's what I'd do in this situ :/ –  Feb 09 '16 at 20:17
  • @Will cleaning the project has gotten me some more info! The error is now "No default constructor found for type 'PSS.MainWindow'" (and of course there isn't). I will have to investigate how to fix that. – Conrad Feb 09 '16 at 21:03
  • Make sure your solution is configured to build the correct projects when debugging! And it's missing a default constructor--just add an empty public constructor to the type. No biggie. –  Feb 09 '16 at 21:15
  • @Will sorry should have mentioned - if I just add the empty default constructor, then _that_ ctor gets called and not the one with the ``MainWindowVM`` arg. So then the MainWindow does not get initialized correctly. – Conrad Feb 09 '16 at 21:22
  • Not familiar with ninject. Constructor injection isn't really compatible with xaml deserialization :/ –  Feb 09 '16 at 21:26
  • 1
    1) Is there some other place, e.g. StartupUri you specify which Window to show? 2) you may need to configure ninject to know how to resolve the types.. like `Container.Bind().ToSelf()`. Though i thought by default this was not necessary (when the type resolves to itself). 3) i suggest you add a `try .. catch..` around the resolution and add a breakpoint in the catch. That'll make it easier to debug than to deal with WPF's `NullReferenceException`... – BatteryBackupUnit Feb 09 '16 at 22:42
  • 2
    @BatteryBackupUnit Ugh total space cadet move - I neglected to remove ``StartupUri="View/MainWindow.xaml"`` from App.xaml. Everything is working as expected now! – Conrad Feb 10 '16 at 15:07
  • Possible duplicate of [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Enigmativity Sep 04 '17 at 09:55
  • @Enigmativity it looks like you didn't read all the comments. The answer, which I mentioned above, (and as answered below by cilerler) isn't mentioned in your "possible duplicate." – Conrad Sep 04 '17 at 15:27
  • @Conrad - The answer I linked to is a very general answer to this problem. It's not intended to solve every specific case. Why did you double-quote the words "possible duplicate"? – Enigmativity Sep 04 '17 at 22:47

1 Answers1

3

I just experienced the same issue with

While I was researching, I found that if I override OnStartup method, I should remove the StartupUri from the App.xaml which solved the issue for me.

Since you are overriding OnStartup too, I believe it will solve it for you too.

cilerler
  • 9,010
  • 10
  • 56
  • 91
  • 1
    My issue was inheriting from FrameworkElement (for a drawing visual host), and I didn't made a parameterless constructor for that class. The moment I reworked the constructor to a parameterless one, the exception went away. Thanks ! (though, what I did was a dumb move to start with, sometimes, you don't realize how careless you are) +1 anyway. – Karl Stephen Jun 21 '21 at 06:34