Skip to content
Simplifying Discord.Net hosting with .NET Generic Host (Microsoft.Extensions.Hosting)
Branch: master
Clone or download
Latest commit 5ff05fe Oct 10, 2019


Build Status NuGet

Discord.Net hosting with Microsoft.Extensions.Hosting. This package provides extensions to a .NET Generic Host (IHostBuilder) that will run a Discord.Net socket/sharded client as a controllable IHostedService. This simplifies initial bot creation and moves the usual boilerplate to a convenient builder pattern.

Discord.Net 2.1.1+ & .NET Core 2.0+ is required.

var builder = new HostBuilder()               
  .ConfigureAppConfiguration(x =>
  .ConfigureLogging(x =>
  .ConfigureDiscordHost<DiscordSocketClient>((context, configurationBuilder) =>
     configurationBuilder.SetDiscordConfiguration(new DiscordSocketConfig
       LogLevel = LogSeverity.Verbose,
       AlwaysDownloadUsers = true,
       MessageCacheSize = 200

  //Omit this if you don't use the command service
  .ConfigureServices((context, services) =>
    //Add any other services here

var host = builder.Build();
using (host)
  await host.Services.GetRequiredService<CommandHandler>().InitializeAsync();
  await host.RunAsync();

Basic Usage

  1. Create a .NET Core application (or retrofit your existing one)

  2. Add the following NuGet packages (at the absolute minimum):

    Discord.Addons.Hosting Microsoft.Extensions.Hosting

  3. Create and start your application using a HostBuilder as shown above and in the examples linked below


Fully working examples are available here

If you want something more advanced, one of my bots CitizenEnforcer uses this extension. You can find it here


Serilog should be added to the host with Serilog.Extensions.Hosting.

See the Serilog example for usage


When shutdown is requested, the host will wait a maximum of 5 seconds for services to stop before timing out.

If you're finding that this isn't enough time, you can modify the shutdown timeout via the ShutdownTimeout host setting.


Discord.Net can occasionally give up trying to reconnect after an extended outage. This library provides a basic solution that will automatically attempt to restart the host on a failure. Please note that this functionality is experimental and won't do much if the client completely deadlocks. This feature is also affected by the shutdown timeout set above.

To use the reliability extensions, start the host with await host.RunReliablyAsync().

To shutdown the host, it's recommended to add a shutdown command to your bot and call host.StopReliablyAsync().

This behaviour is similar to the usage of RunAsync() and StopAsync()

You can’t perform that action at this time.