Search code examples
c#wpfdependency-injectionninjectioc-container

WPF with Dependency Injection using Ioc


I am currently learning how to code in WPF desktop application, and I am following this show a super old tutorial on youtube on the subject: https://www.youtube.com/watch?v=w5kAUCFDRy4&list=PLrW43fNmjaQVYF4zgsD0oL9Iv6u23PI6M&index=11

I have trouble using Dependency injection with multiple projects using the Ninject framework. I created a public static class called IocContainer that binds all of the required view models based on a class named application view models and gets the service of the IOC of the specific target. Snipped of the overall class is shown.

    /// <summary>
    /// Sets up the Container, binds all information required and is ready for use
    /// NOTE: must be called as soon as your application starts up to ensure all services can
    /// be called.
    /// </summary>
    public static void Setup()
    {
        //Binds all required view models
        BindViewModels();
    }

    /// <summary>
    /// Binds all signeleton view models
    /// </summary>
    /// <exception cref="NotImplementedException"></exception>
    private static void BindViewModels()
    {
        //Binds to a signle instance of Application View Model
        Kernel.Bind<ApplicationViewModel>().ToConstant(new ApplicationViewModel());
    }

    #endregion

    /// <summary>
    /// Get a serice of the IOC of the specific target 
    /// </summary>
    /// <typeparam name="T"> ttype to get</typeparam>
    /// <returns></returns>
    /// <exception cref="NotImplementedException"></exception>
    public static object Get<T>()
    {
        return Kernel.Get<T>();
    }

The IocContainer gets called on a overrides Onstartup function of the WPF to set up the IOC, and the application class has a Public enum variable named current age. However, when I attempt to change to a different page when running a task, it says that ApplicationViewModel the object does not contain the definition even though it does exist. ApplicationViewModel is located in a different project named Project.Core. And I attempt to change the current page value by doing the following:

//Located in the Application view model
public ApplicationPage CurrentPage { get; set; }
//attempt to change the current page inside my page view model
IocContainer.Get<ApplicationViewModel>().CurrentPage = ApplicationPage.Connection;

Error code: Severity Code Description Project File Line Suppression State Error CS1061 'object' does not contain a definition for 'CurrentPage' and no accessible extension method 'CurrentPage' accepting a first argument of type 'object' could be found

Any ideas or suggestions? Thanks, Jorge Jurado-Garcia


Solution

  • Your service locator class Get<T>() method returns an object type and not the requested type.

    It should return T.

    public static T Get<T>()
    {
        return Kernel.Get<T>();
    }