use SqlDependency with [ORM]

3

I'm developing a service that should perform a procedure whenever a record as a given condition is inserted into the database.

However, although you are using SqlDependency , I am not using SqlCommand , it is running and then discarded.

static class Program
{
    static void Main()
    {
        ServiceBase[] ServicesToRun;
        ServicesToRun = new ServiceBase[]
        {
            new MyService()
        };
        ServiceBase.Run(ServicesToRun);
    }
}


public partial class MyService : ServiceBase
{
    private bool IsRunning;

    private static string ConnectionString
    {
        get
        {
            return ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString;
        }
    }

    public MyService()
    {   
        InitializeComponent();
    }

    protected override void OnStart(string[] args)
    {            
        this.IsRunning = true;
        this.Agendar();
    }

    protected override void OnStop()
    {
        this.IsRunning = false;
    }

    private void Agendar()
    {
        if (!this.IsRunning)
            return;
        var processo = Task.Run(Processar);
        processo.ContinueWith(task =>
        {
            Console.WriteLine(task.Exception);
        }, TaskContinuationOptions.OnlyOnFaulted);
    }

    private async Task Processar()
    {
        using (var comando = new SqlCommand(Properties.Resources.MyQueryName))
        {
            var depedency = default(SqlDependency);
            var handler = default(OnChangeEventHandler);
            handler = new OnChangeEventHandler(async (sender, e) => {
                depedency = sender as SqlDependency;
                if (depedency != null) {
                    depedency.OnChange -= handler;
                    comando.Notification = null;
                }

                depedency = new SqlDependency(comando);
                depedency.OnChange += handler;

                using (var conexao = new SqlConnection(Program.ConnectionString))
                {
                    await conexao.OpenAsync();
                    comando.Connection = conexao;
                    (await comando.ExecuteReader()).Close();
                }

                if (e == null || e.Info == SqlNotificationInfo.Insert)
                    this.DoSomeWork();
            });
            handler.Invoke(depedency, null);
        }
    }

    private async Task DoSomeWork()
    {
        using (var contexto = new MyDbContext())
        {
            // regras de negocio.
        }
    }
}

So, is there a more elegant solution than the one shown below?

(await comando.ExecuteReaderAsync()).Close();
    
asked by anonymous 30.03.2017 / 20:33

0 answers