C
C#17mo ago
mario12136

Transition to Microsoft's Dependency Injection Library

https://gist.github.com/MarioFares/f935dd74aa461feefb227631af1c2b3e I was wondering what I can do to improve my App.xaml.cs file. I have seen this https://learn.microsoft.com/en-us/dotnet/communitytoolkit/mvvm/ioc but one of my service implementations takes an argument and I am not sure how best to do that. Otherwise, I am not sure if I am doing anything wrong.
Gist
Startup
Startup. GitHub Gist: instantly share code, notes, and snippets.
Ioc - .NET Community Toolkit
An introduction to the use of the IServiceProvider type through the Microsoft.Extensions.DependencyInjection APIs
2 Replies
Angius
Angius17mo ago
The .AddX<IInterface, IImplementation>() have an overload that lets you provide the default implementation So, for example,
var seed = Random.Shared.Next();
services.AddSingleton<IRandomizer, TileRandomizer>(new TileRandomizer(seed)));
var seed = Random.Shared.Next();
services.AddSingleton<IRandomizer, TileRandomizer>(new TileRandomizer(seed)));
mario12136
mario12136OP17mo ago
I have a few questions about working with DI in WPF 1. Do I make all my views and view models services using services.Add...<>(). 2. Do I need to add models as services or should I avoid altogether having any contrusctors take models. 3. If I have a settings class that I want to access throught the entire, what is the best way to make it accessble. I tried this
public IHost? AppHost { get; private set; }

public new static App Current => (App)Application.Current;

public Settings Settings => AppHost!.Services.GetRequiredService<Settings>();
public IHost? AppHost { get; private set; }

public new static App Current => (App)Application.Current;

public Settings Settings => AppHost!.Services.GetRequiredService<Settings>();
and in any code I just say App.Current.Settings...
Want results from more Discord servers?
Add your server