Skip to content

Instantly share code, notes, and snippets.

@Keboo
Created June 20, 2022 18:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Keboo/4751263a6969b8dce34310e642142a32 to your computer and use it in GitHub Desktop.
Save Keboo/4751263a6969b8dce34310e642142a32 to your computer and use it in GitHub Desktop.
MarkupExtension with DI
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
});
}
public interface IService { }
public class Service : IService { }
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