Skip to content

Instantly share code, notes, and snippets.

@Platonenkov
Last active June 29, 2021 08:51
Show Gist options
  • Save Platonenkov/7dd4a7ee5a83a86426e335833aab4264 to your computer and use it in GitHub Desktop.
Save Platonenkov/7dd4a7ee5a83a86426e335833aab4264 to your computer and use it in GitHub Desktop.
Add Host, service
public partial class App
{
public static bool IsDesignMode { get; private set; } = true;
private static IHost __Host;
public static IHost Host => __Host ??= Program.CreateHostBuilder(Environment.GetCommandLineArgs()).Build();
protected override async void OnStartup(StartupEventArgs e)
{
IsDesignMode = false;
var host = Host;
base.OnStartup(e);
await host.StartAsync().ConfigureAwait(false);
}
protected override async void OnExit(ExitEventArgs e)
{
base.OnExit(e);
var host = Host;
await host.StopAsync().ConfigureAwait(false);
host.Dispose();
__Host = null;
}
public static void ConfigureServices(HostBuilderContext host, IServiceCollection services) => services
.RegisterServices()
.RegisterViewModels();
public static string CurrentDirectory => IsDesignMode
? Path.GetDirectoryName(GetSourceCodePath())
: Environment.CurrentDirectory;
private static string GetSourceCodePath([CallerFilePath] string Path = null) => Path;
}
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Hosting" Version="3.1.5" />
</ItemGroup>
using Microsoft.Extensions.DependencyInjection;
internal static class Registrator
{
public static IServiceCollection RegisterServices(this IServiceCollection services)
{
services.AddSingleton<IService, Service>();
//services.AddTransient<IService, Service>();
//services.AddScoped<IService, Service>();
return services;
}
public static IServiceCollection RegisterViewModels(this IServiceCollection services)
{
services.AddSingleton<MainWindowViewModel>();
//services.AddTransient<MainWindowViewModel>();
return services;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment