Внедрение недвижимости - PullRequest
       15

Внедрение недвижимости

0 голосов
/ 22 апреля 2019

Я пытаюсь создать бот-телеграмму с напоминанием. Я использую Telegram.Bot 14.10.0, Quartz 3.0.7, .net core 2.0. Первая версия должна: получить сообщение «напоминание» из телеграммы, создать задание (используя Кварц) и отправить обратно через 5 секунд. Мое консольное приложение с DI выглядит так:

Program.cs
static IBot _botClient;

public static void Main(string[] args)
{
    // it doesn't matter    
    var servicesProvider = BuildDi(connecionString, section);
    _botClient = servicesProvider.GetRequiredService<IBot>();
    _botClient.Start(appModel.BotConfiguration.BotToken, httpProxy);
    var reminderJob = servicesProvider.GetRequiredService<IReminderJob>();
    reminderJob.Bot = _botClient;

    Console.ReadLine();
    _botClient.Stop();
    // it doesn't matter    
}

private static ServiceProvider BuildDi(string connectionString, IConfigurationSection section)
{
    var rJob = new ReminderJob();
    var sCollection = new ServiceCollection()
        .AddSingleton<IBot, Bot>()
        .AddSingleton<ReminderJob>(rJob)
        .AddSingleton<ISchedulerBot>(s =>
        {
            var schedBor = new SchedulerBot();
            schedBor.StartScheduler();
            return schedBor;
        });
    return sCollection.BuildServiceProvider();
}   

Bot.cs
public class Bot : IBot
{
    static TelegramBotClient _botClient;
    public void Start(string botToken, WebProxy httpProxy)
    {
        _botClient = new TelegramBotClient(botToken, httpProxy);
        _botClient.OnReceiveError += BotOnReceiveError;
        _botClient.OnMessage += Bot_OnMessage;
        _botClient.StartReceiving();
    }

    private static async void Bot_OnMessage(object sender, MessageEventArgs e)
    {
        var me = wait _botClient.GetMeAsync();
        if (e.Message.Text == "reminder")
        {
            var map= new Dictionary<string, object> { { ReminderJobConst.ChatId, e.Message.Chat.Id.ToString() }, { ReminderJobConst.HomeWordId, 1} };
            var job = JobBuilder.Create<ReminderJob>().WithIdentity($"{prefix}{rnd.Next()}").UsingJobData(new JobDataMap(map)).Build();

            var trigger = TriggerBuilder.Create().WithIdentity($"{prefix}{rnd.Next()}").StartAt(DateTime.Now.AddSeconds(5).ToUniversalTime())
                .Build();
            await bot.Scheduler.ScheduleJob(job, trigger);
        }
    }
}

Quartz.net не позволяет использовать конструктор с DI. Вот почему я пытаюсь создать собственность с DI. ReminderJob.cs

public class ReminderJob : IJob
{
    static IBot _bot;
    public IBot Bot { get; set; }
    public async Task Execute(IJobExecutionContext context)
    {
        var parameters = context.JobDetail.JobDataMap;
        var userId = parameters.GetLongValue(ReminderJobConst.ChatId);
        var homeWorkId = parameters.GetLongValue(ReminderJobConst.HomeWordId);

        await System.Console.Out.WriteLineAsync("HelloJob is executing.");
    }
}

Как передать _botClient на напоминание в Program.cs?

1 Ответ

0 голосов
/ 28 апреля 2019

Если кто-то ищет ответ, у меня есть один: Program.cs (в Main)

var schedBor = servicesProvider.GetRequiredService<ISchedulerBot>();
        var logger = servicesProvider.GetRequiredService<ILogger<DIJobFactory>>();
        schedBor.StartScheduler();
        schedBor.Scheduler.JobFactory = new DIJobFactory(logger, servicesProvider);

DIJobFactory.cs

public class DIJobFactory : IJobFactory
{
    static ILogger<DIJobFactory> _logger;
    static IServiceProvider _serviceProvider;
    public DIJobFactory(ILogger<DIJobFactory> logger, IServiceProvider sp)
    {
        _logger = logger;
        _serviceProvider = sp;
    }

    public IJob NewJob(TriggerFiredBundle bundle, IScheduler scheduler)
    {
        IJobDetail jobDetail = bundle.JobDetail;
        Type jobType = jobDetail.JobType;
        try
        {
            _logger.LogDebug($"Producing instance of Job '{jobDetail.Key}', class={jobType.FullName}");

            if (jobType == null)
            {
                throw new ArgumentNullException(nameof(jobType), "Cannot instantiate null");
            }
            return (IJob)_serviceProvider.GetRequiredService(jobType);
        }
        catch (Exception e)
        {
            SchedulerException se = new SchedulerException($"Problem instantiating class '{jobDetail.JobType.FullName}'", e);
            throw se;
        }

    }
    // get from https://github.com/quartznet/quartznet/blob/139aafa23728892b0a5ebf845ce28c3bfdb0bfe8/src/Quartz/Simpl/SimpleJobFactory.cs
    public void ReturnJob(IJob job)
    {
        var disposable = job as IDisposable;
        disposable?.Dispose();
    }
}

ReminderJob.cs

public interface IReminderJob : IJob
{
}
public class ReminderJob : IReminderJob
{
    ILogger<ReminderJob> _logger;
    IBot _bot;
    public ReminderJob(ILogger<ReminderJob> logger, IBot bot)
    {
        _logger = logger;
        _bot = bot;
    }
    public async Task Execute(IJobExecutionContext context)
    {
        var parameters = context.JobDetail.JobDataMap;
        var userId = parameters.GetLongValue(ReminderJobConst.ChatId);
        var homeWorkId = parameters.GetLongValue(ReminderJobConst.HomeWordId);
        await _bot.Send(userId.ToString(), "test");

    }
}
...