Created
June 20, 2022 18:07
-
-
Save Keboo/4751263a6969b8dce34310e642142a32 to your computer and use it in GitHub Desktop.
MarkupExtension with DI
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public partial class App : Application | |
{ | |
[NotNull] | |
public static IServiceProvider? ServiceProvider { get; private set; } | |
[STAThread] | |
public static void Main(string[] args) | |
{ | |
using IHost host = CreateHostBuilder(args).Build(); | |
host.Start(); | |
ServiceProvider = host.Services; | |
App app = new(); | |
app.InitializeComponent(); | |
app.MainWindow = host.Services.GetRequiredService<MainWindow>(); | |
app.MainWindow.Visibility = Visibility.Visible; | |
app.Run(); | |
} | |
public static IHostBuilder CreateHostBuilder(string[] args) => | |
Host.CreateDefaultBuilder(args) | |
.ConfigureAppConfiguration((hostBuilderContext, configurationBuilder) => | |
{ | |
//TODO: Any config setup here | |
}) | |
.ConfigureServices((hostContext, services) => | |
{ | |
services.AddSingleton<MainWindow>(); | |
services.AddSingleton<MainWindowViewModel>(); | |
services.AddSingleton<IService, Service>(); | |
//TODO: Register services | |
}); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public interface IService { } | |
public class Service : IService { } |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class TestExtension : MarkupExtension | |
{ | |
// Default ctor needed for XAML instantitation | |
public TestExtension() | |
: this(App.ServiceProvider.GetService<IService>()!) | |
{ } | |
//Overloaded constructor to make testing easier | |
public TestExtension(IService service) | |
{ | |
Service = service ?? throw new ArgumentNullException(nameof(service)); | |
} | |
private IService Service { get; } | |
public override object? ProvideValue(IServiceProvider serviceProvider) | |
{ | |
//TODO Use dependencies, produce value | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment