Catel/Ninject: Ninject.ActivationException when re

2019-09-17 18:35发布

问题:

when i was trying to resolve the IUIVisualizerService a Ninject.ActivationException came up in Ninject.dll.

Can someone help me pls?

This code section calls the problem:

NinjectDependencyResolver resolver = new NinjectDependencyResolver();
            var item = resolver.GetService<IUIVisualizerService>();

Code for Resolver:

using System;
    using System.Collections.Generic;
    using Catel.Services;
    using Ninject;
    using NLog;

    namespace MS_Modell.Infrastructure
    {
        internal class NinjectDependencyResolver
        {
            private IKernel kernel;
            private Logger log = LogManager.GetCurrentClassLogger();

            public NinjectDependencyResolver()
            {
                try
                {
                    kernel = new StandardKernel();
                    kernel.Bind<IUIVisualizerService>().To<UIVisualizerService>();
                }
                catch (Exception ex)
                {
                    log.Fatal("NinjectDependencyResolver(): " + ex);
                    throw;
                }
            }

            public T GetService<T>()
            {
                try
                {
                    return kernel.TryGet<T>();
                }
                catch (Exception ex)
                {
                    log.Fatal("GetService<T>(): " + ex.Message);
                    throw;
                }
            }       
        }
    }

Edit: I got a null object after GetService is called. But the exception wasnt raised. Only a message on the console output of Visual Studio can be seen:

An expcetion (first chance) of type "Ninject.ActivationException" was thrown in Ninject.dll.

Edit 2:

Thx guys for the fast answers. Here is the concrete solution for someone, who runs into the same problem:

In NinjectResolver you need to add this code:

    kernel.Bind<IViewLocator>().To<ViewLocator>();
    kernel.Bind<IUIVisualizerService>().To<UIVisualizerService>().WithConstructorArgument("ViewLocator", GetService<IViewLocator>());

Resolving the IUIVisualizerService:

TargetSelectorViewModel selector = new TargetSelectorViewModel();
                var item = resolver.GetService<IUIVisualizerService>();
                item.Register(typeof(TargetSelectorViewModel), typeof(TargetSelector));
                item.ShowDialog(selector);

回答1:

The UIVisualizerService requires dependency injection of the IViewLocator. Make sure that Ninject can resolve that as well.

https://github.com/Catel/Catel/blob/develop/src/Catel.MVVM/Catel.MVVM.NET40/Services/UIVisualizerService.cs#L54



标签: c# ninject catel