Trying Dependency Injection Without Success

Scottintexas

Well-known member
Joined
Jun 21, 2018
Messages
47
Location
Texas
Programming Experience
5-10
Second attempt!

I am trying to inject a logger into my MainWindowViewModel.
C#:
        /// <summary>
        /// Entry point for application.
        /// </summary>
        /// <param name="e"></param>
        protected override async void OnStartup(StartupEventArgs e)
        {
            await AppHost!.StartAsync();
            var startupForm = AppHost.Services.GetRequiredService<MainWindowView>();
            startupForm.DataContext = AppHost.Services.GetRequiredService<MainWindowViewModel>();
            startupForm.Show();
            base.OnStartup(e);
        }

        /// <summary>
        /// Application default constructor.
        /// </summary>
        public App()
        {
            AppHost = Host.CreateDefaultBuilder()
                .ConfigureServices((HostBuilderContext, services) =>
                {
                    services.AddSingleton<MainWindowView>();
                    services.AddSingleton<IMyLogger, MyLogger>();
                    services.AddSingleton<MainWindowViewModel>(serviceProvider =>
                    {
                        var paramVal = serviceProvider.GetRequiredService<MyLogger>();
                        return new MainWindowViewModel(paramVal);
                    });
                })
                .Build();
        }

My MainWindowViewModel constructor takes an argument of type MyLogger. But what I think is right is not working. I am getting the exception "
System.InvalidOperationException: 'No service for type 'Izod_Impact.Loggers.MyLogger' has been registered.'" But isn't that what line 6 does?

Any help would be appreciated. What I want to do is write to a log file, not Microsoft logging extension.

Thank you.
 
Solution
But isn't that what line 6 does?

Line 6 is an opening brace

If you mean line 23, then that line registers for a type of IMyLogger, but you've written your constructor to take a MyLogger. Either register the concrete type, or have the constructor take the interface type
But isn't that what line 6 does?

Line 6 is an opening brace

If you mean line 23, then that line registers for a type of IMyLogger, but you've written your constructor to take a MyLogger. Either register the concrete type, or have the constructor take the interface type
 
Solution
Line 6 is an opening brace

If you mean line 23, then that line registers for a type of IMyLogger, but you've written your constructor to take a MyLogger. Either register the concrete type, or have the constructor take the interface type

Sorry. Line 23.
 
Back
Top Bottom