Skip to content

Added Microsoft.Extensions.Hosting support #18

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: master
Choose a base branch
from

Conversation

GerardSmit
Copy link
Contributor

This PR adds Microsoft.Extensions.Hosting support to Miki.Framework. This makes it way easier to set-up a new bot in a console application or even a ASP.NET Core application.

Middlewares

This PR introduces IBotApplicationBuilder which is equal to IApplicationBuilder in ASP.Net Core.

You can define middlewares in ConfigureBot:

HostBuilder.ConfigureBot(app =>
{
    app.Use(async (context, func) =>
    {
        var channel = await context.Message.GetChannelAsync();

        await channel.SendMessageAsync("Hello world!")
    });
})

Command pipeline

To use a command stage in the new middleware, you can use app.UseStage<ClassName>().
To use the CommandPipelineBuilder extensions, you can use app.UsePipeline:

app.UsePipeline(builder =>
{
    builder.UsePrefixes();
    builder.UseArgumentPack();
    builder.UseCommandHandler();
});

Example bot

public static Task Main(string[] args)
{
    return new HostBuilder()
        .ConfigureServices(services =>
        {
            services.AddDiscord("TOKEN");
            services.AddCacheClient<InMemoryCacheClient>();
            services.AddSingleton<ISerializer, ProtobufSerializer>();
        })
        .ConfigureBot(app =>
        {
            app.UseStage<FetchDataStage>();
            app.Use(async (context, next) =>
            {
                var message = context.Message;

                if (message.Content == "ping")
                {
                    await context.GetChannel().SendMessageAsync("Pong");
                }

                await next();
            });
        })
        .RunConsoleAsync();
}

@GerardSmit GerardSmit requested a review from velddev June 25, 2020 20:50
@GerardSmit GerardSmit marked this pull request as draft June 25, 2020 22:51
It's now possible to inject scoped services in the module constructor. It's also possible to make a custom parameter provider with IParameterProvider.
@GerardSmit GerardSmit marked this pull request as ready for review June 26, 2020 21:16
@GerardSmit GerardSmit mentioned this pull request Jun 26, 2020
2 tasks
Copy link
Member

@velddev velddev left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lets some questions and remarks


public CommandTree Create(Assembly assembly)

public IServiceCollection Services { get; }
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why are these public now? they shouldn't be used externally.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So you can easily add services when you make an extension method, e.g.:

public static class CommandExtensions
{
    public static CommandTreeBuilder AddWarningsModule(this CommandTreeBuilder builder)
    {
        builder.Services.AddScoped<IWarningService, WarningService>();
        builder.AddAssembly(typeof(CommandExtensions).Assembly);
        return builder;
    }
}

Now you can call the extension method AddWarningsModule and all the required services are added:

services.AddCommands(builder =>
{
    builder.AddWarningsModule();
});


namespace Miki.Framework.Commands
{
internal class CommandTreeCompiler
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we perhaps have any test cases for this?

@@ -16,15 +16,15 @@ public abstract class Node
public IReadOnlyCollection<Attribute> Attributes => Type.GetCustomAttributes<Attribute>(false)
.ToList();

private MemberInfo Type { get; }
public Type Type { get; }
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What's the reasoning for this?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This was needed when the delegate is being compiled, I need the parent type when creating the NodeExecutable:

https://github.com/Mikibot/Miki.Framework/blob/ede6821a96fc622a3e12c308dc2e73797dc816d4/src/Miki.Framework.Commands/CommandTreeCompiler.cs#L101

}
catch (Exception e)
{
Log.Error(e);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this before the pipeline?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, this is after the pipeline. This is called when an exception occurred in the middelware.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we add an event then when an exception occurs to fetch the current context state and exception?

@@ -9,6 +12,11 @@
/// </summary>
public interface IContext
{
/// <summary>
/// The message received from discord.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"The message recieved from Discord" is deceiving, it will change into more providers in the future.

throw new ArgumentNullException(nameof(handler));
}

app.Use(_ => handler);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nani?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The extension method .Run is being used at the end of the pipeline, so you don't need the next middleware. This is the same as ASP.NET Core.

/// <returns></returns>
public static IBotApplicationBuilder UseWhen(this IBotApplicationBuilder app, Predicate predicate, Action<IBotApplicationBuilder> configuration)
{
if (app == null)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

App can't be null here right? Either way, you can use Required<IBotApplicationBuilder> to automate the process.

Copy link
Contributor Author

@GerardSmit GerardSmit Jun 27, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

App can't be null here right?

Probably not, this is how Microsoft implemented UseWhen as well but I can remove this.

Either way, you can use Required to automate the process.

Required<IBotApplicationBuilder> is not possible because it's an extension method. It would register the extension method to Required<IBotApplicationBuilder> instead of IBotApplicationBuilder.

Copy link
Member

@velddev velddev Jun 27, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fair enough, but the other params could have it set to required.

public static IServiceCollection AddCacheClient<T>(this IServiceCollection services)
where T : class, IExtendedCacheClient
{
services.AddSingleton<ICacheClient>(provider => provider.GetService<IExtendedCacheClient>());
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How does this work?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IExtendedCacheClient extends ICacheClient. This registration redirects ICacheClient to IExtendedCacheClient, you could register it two times but that means you have (for example) two Redis connections open.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That doesn't make sense, we already have connection pooling.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants