mardi 12 mars 2019

c# Intercept constructor parameters

I am attempting to write a job queuing system using C#.

Suppose I have the following class which represents a job to perform at a later date:

  public class TestJob : QueuableJob
    {
        private readonly string _t;
        private readonly string _e;
        public TestJob(string t, string e)
        {
            _t = t;
            _e = e;

        }
        public Task PerformWork(ITestService testService)
        {
            testService.Message($"Hello: {_t} {_e}");
            return Task.CompletedTask;
        }
    }

I would like to be able to call something like:

JobQueueService.EnqueueJob(new TestJob("value1", "value2"));

In order to queue a job, I need serialize the parameters passed to the constructor of TestJob, so I can store them in a persistence layer (eg a database) and later deserialize them. Then I can instantiate the class and execute PerformWork. I would like to handle this as seamless as possible in my library so the end-user writing their "Job" classes doesn't have to worry about adding specific things for serialization.

I cannot figure out a way to "intercept" the parameters passed to the TestJob class without either losing strict typing (eg I could use params object[] parameters), or forcing the end user to implement some other code to help with serialization.

Currently, the most elegant solution I can think of (for the end user), is something like this:

public class TestJob : QueuableJob
    {
        private readonly string _t;
        private readonly string _e;
        public TestJob(string t, string e) : base(t,e)
        {
            _t = t;
            _e = e;

        }
        public Task PerformWork(ITestService testService)
        {
            testService.Message($"Hello: {_t} {_e}");
            return Task.CompletedTask;
        }
    }

However, that would require the developer to remember to pass all of their parameters to base() (like base(t,e) in the example above). The compiler will not complain if they forget to do this, so it could be source of tricky bugs. I've also tried to get the information using System.Diagnostics.StackTrace in the QueuableJob constructor, however it don't believe I can obtain the values of the parameters from the stack.

Is there any way I can use reflection to "intercept" what is being passed into the TestJob constructor?





Aucun commentaire:

Enregistrer un commentaire