Skip to content

Commit 4b52e3a

Browse files
committed
Refactor bot framework and controller registration
Restructure the TelegramBot application by removing the `MapControllers` method from the `IBot` interface and implementing the `AddBotControllers` extension method in `ServiceCollectionExtensions`. This change allows for direct registration of bot controllers into the service collection, enhancing modularity and maintainability. The `Run` method in `BotApp` has been simplified, and the `BotControllerMethodsContainer` is now instantiated within the new extension method.
1 parent bdb23fc commit 4b52e3a

6 files changed

Lines changed: 39 additions & 45 deletions

File tree

Sources/TelegramBot.ConsoleTest/Program.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ public static void Main(string[] args)
1515
.UseApiKey(x => x.FromConfiguration());
1616

1717
builder.Services
18+
.AddBotControllers()
1819
.RegisterCommands(x =>
1920
{
2021
x.RegisterCommand("/start", "initiates the bot")
@@ -35,9 +36,8 @@ public static void Main(string[] args)
3536
}, "ru")
3637
.AddDbContext<AppDbContext>(x => x.UseSqlite("Data Source=app.db"))
3738
.UseAuthorizationHandler<AuthorizationHandler>();
39+
3840
var app = builder.Build();
39-
app.MapControllers();
40-
4141
app.Run();
4242
}
4343
}

Sources/TelegramBot/BotApp.cs

Lines changed: 0 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,7 @@
11
using System;
2-
using System.Linq;
32
using System.Threading;
4-
using System.Reflection;
53
using TelegramBot.Services;
64
using System.Threading.Tasks;
7-
using TelegramBot.Containers;
8-
using TelegramBot.Controllers;
95
using System.Collections.Generic;
106
using Microsoft.Extensions.Hosting;
117
using Microsoft.Extensions.Logging;
@@ -39,33 +35,6 @@ public BotApp(ServiceProvider serviceProvider)
3935
_logger = serviceProvider.GetRequiredService<ILogger<BotApp>>();
4036
}
4137

42-
/// <summary>
43-
/// Maps controllers inherited from <see cref="BotControllerBase"/>.
44-
/// </summary>
45-
public IBot MapControllers()
46-
{
47-
CheckDisposed();
48-
var types = Assembly.GetCallingAssembly().GetTypes();
49-
List<Type> result = new List<Type>();
50-
foreach (var type in types)
51-
{
52-
if (type.IsSubclassOf(typeof(BotControllerBase)))
53-
{
54-
result.Add(type);
55-
}
56-
}
57-
var controllerMethods = result
58-
.SelectMany(t => t.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly))
59-
.ToList();
60-
BotControllerMethodsContainer container = _serviceProvider.GetService<BotControllerMethodsContainer>()
61-
?? throw new InvalidOperationException("Bot controller methods container is not registered.");
62-
foreach (var method in controllerMethods)
63-
{
64-
container.AddMethod(method);
65-
}
66-
return this;
67-
}
68-
6938
/// <summary>
7039
/// Runs the bot.
7140
/// </summary>

Sources/TelegramBot/Builders/BotBuilder.cs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -190,7 +190,6 @@ public IBot Build()
190190
}
191191
Services.AddHostedService<TelegramBotHostedService>();
192192
Services.AddSingleton(_botConfiguration);
193-
Services.AddSingleton<BotControllerMethodsContainer>();
194193
return new BotApp(Services.BuildServiceProvider());
195194
}
196195
}

Sources/TelegramBot/Extensions/ServiceCollectionExtensions.cs

Lines changed: 34 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,12 @@
11
using System;
2+
using System.Linq;
3+
using System.Reflection;
24
using TelegramBot.Builders;
35
using TelegramBot.Attributes;
6+
using TelegramBot.Containers;
7+
using TelegramBot.Controllers;
48
using TelegramBot.Abstractions;
9+
using System.Collections.Generic;
510
using Microsoft.Extensions.DependencyInjection;
611

712
namespace TelegramBot.Extensions
@@ -11,9 +16,36 @@ namespace TelegramBot.Extensions
1116
/// </summary>
1217
public static class ServiceCollectionExtensions
1318
{
19+
/// <summary>
20+
/// Registers the bot controllers in the service collection. <br/>
21+
/// </summary>
22+
/// <param name="services">The service collection.</param>
23+
/// <returns>The modified service collection with bot controllers registered.</returns>
24+
public static IServiceCollection AddBotControllers(this IServiceCollection services)
25+
{
26+
var types = Assembly.GetCallingAssembly().GetTypes();
27+
List<Type> result = new List<Type>();
28+
foreach (var type in types)
29+
{
30+
if (type.IsSubclassOf(typeof(BotControllerBase)))
31+
{
32+
result.Add(type);
33+
}
34+
}
35+
var controllerMethods = result
36+
.SelectMany(t => t.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly))
37+
.ToList();
38+
BotControllerMethodsContainer container = new BotControllerMethodsContainer();
39+
foreach (var method in controllerMethods)
40+
{
41+
container.AddMethod(method);
42+
}
43+
return services.AddSingleton(container);
44+
}
45+
1446
/// <summary>
1547
/// Register commands for the bot. This method only registers the commands in Telegram UI. <br/>
16-
/// Controllers should be registered separately with <see cref="IBot.MapControllers"/> <br/>
48+
/// Controllers should be registered separately with <see cref="AddBotControllers(IServiceCollection)"/> <br/>
1749
/// You can use commands even without this method.
1850
/// </summary>
1951
/// <param name="services">The service collection.</param>
@@ -24,8 +56,7 @@ public static IServiceCollection RegisterCommands(this IServiceCollection servic
2456
{
2557
CommandRegistrationBuilder builder = new CommandRegistrationBuilder(language);
2658
setup(builder);
27-
services.AddSingleton(builder);
28-
return services;
59+
return services.AddSingleton(builder);
2960
}
3061

3162
/// <summary>

Sources/TelegramBot/IBot.cs

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
using System.Threading;
2-
using TelegramBot.Controllers;
32
using Microsoft.Extensions.Hosting;
43

54
namespace TelegramBot
@@ -9,11 +8,6 @@ namespace TelegramBot
98
/// </summary>
109
public interface IBot : IHost
1110
{
12-
/// <summary>
13-
/// Maps controllers inherited from <see cref="BotControllerBase"/>.
14-
/// </summary>
15-
IBot MapControllers();
16-
1711
/// <summary>
1812
/// Runs the bot.
1913
/// </summary>

Sources/TelegramBot/Services/TelegramBotHostedService.cs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,14 +30,15 @@ internal class TelegramBotHostedService : IHostedService
3030

3131
public TelegramBotHostedService(BotConfiguration botConfiguration, ITelegramBotClient telegramBotClient,
3232
ILogger<TelegramBotHostedService> logger, IServiceProvider serviceProvider,
33-
BotControllerMethodsContainer botControllerMethodsContainer)
33+
BotControllerMethodsContainer? botControllerMethodsContainer)
3434
{
3535
_logger = logger;
3636
_client = telegramBotClient;
3737
_serviceProvider = serviceProvider;
3838
_botConfiguration = botConfiguration;
39-
_methods = botControllerMethodsContainer.Methods;
4039
_cancellationTokenSource = new CancellationTokenSource();
40+
_methods = botControllerMethodsContainer?.Methods ?? new List<MethodInfo>();
41+
_logger.LogInformation("Telegram bot hosted service initialized with {methodCount} methods.", _methods.Count);
4142
}
4243

4344
public async Task StartAsync(CancellationToken cancellationToken)

0 commit comments

Comments
 (0)