Search code examples
c#mvvmninjectinversion-of-controlcatel

Catel with Ninject


Our company is using Ninject for DI. I have to create a WPF App with MVVM and want to use Catel. Because our services which have the DB DataContext are injected with Ninject, I don't know where to start.

I've started with a prepared skeleton project. This is what App.xaml.cs contains:

public partial class App : Application
{
    public IKernel Container;

    protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);
        ConfigureContainer();
        ComposeObjects();
        Current.MainWindow.Show();
    }

    private void ConfigureContainer()
    {
        var modules = new INinjectModule[]
            {
                new ServiceModule()
            };

        Container = new StandardKernel(modules);
    }

    private void ComposeObjects()
    {
        Current.MainWindow = Container.Get<MainWindow>();
        Current.MainWindow.Title = "DI with Ninject";
    }
}

The ServiceModule is inherited from NinjectModule.

With that code I can use this constructor of my MainWindow:

public MainWindow(IAuthenticationService authenticationService)
{
    InitializeComponent();
    ViewModel = new MainWindowViewModel(authenticationService);
    DataContext = ViewModel;
}

The IAuthenticationService is injected via App.xaml.cs and Ninject. In my opinion this solution is hard to maintain, because if I need a new service, I have to add it to the constructor of my MainWindow. Now I need the same thing to work with Catel, but I haven't found something in the documentation.

EDIT: I've found on the documentation that I can register an external IoC container. How do I create my own component (doc: Replacing the default components) which works with the Ninject's standard kernel?

Also is this a good approach of DI or are there better solutions?


Solution

  • Please see the recommended approach on how to replace the default IoC components:

    https://catelproject.atlassian.net/wiki/display/CTL/Replacing+the+default+components

    To create your own component, let the Ninject kernel implement the right interface (for example, IDependencyResolver or IServiceLocator) and all should be set.