Using a DI container in a simple case like this is actually not very much for you. This starts to make more sense when things get more complicated, and also minimizes the effect of dependency changes.
Say, for example, you have an ILoggingService service that all your dependencies are now using. When using a DI container such as Unity, you should add only one line of code.
protected override void OnStartup(StartupEventArgs e) { IUnityContainer container = new UnityContainer(); container.RegisterType<IDialogService, ModalDialogService>(); container.RegisterType<IEventRepository, EventRepository>(); container.RegisterType<ILoggingService, LoggingService>();
When doing this, you must add one line of code and change 3 lines of code.
protected override void OnStartup(StartupEventArgs e) { ILoggingService loggingService = new LoggingService(); // added IDialogService dialogService = new ModalDialogService(loggingService); // modified IEventRepository eventRepository = new EventRepository(loggingService); // modified MainWindow window = new MainWindow(); window.DataContext = new MainWindowViewModel(eventRepository, dialogService, loggingService); // modified window.Show(); }
When using more advanced containers that can scan types for registration, you may not have to change the code at the root of your composition. Here is an example of using AutoFac.
protected override void OnStartup(StartupEventArgs e) { var builder = new ContainerBuilder(); var assembly = Assembly.GetExecutingAssembly(); builder.RegisterAssemblyTypes(assembly) .AsSelf() .AsImplementedInterfaces(); var container = builder.Build(); MainWindow window = container.Resolve<MainWindow>(); window.DataContext = container.Resolve<MainWindowViewModel>(); window.Show(); }
Tim b source share