我为调度作业创建了以下抽象:
public interface IJobData
{ }
public interface IJob<in TJobData> where TJobData : IJobData
{
Task ExecuteAsync(TJobData jobData);
}我在应用层中使用这个来创建工作。例如。
public record ForgotPasswordJobData() : IJobData;
public class ForgotPasswordJob : IJob<ForgotPasswordJobData>
{
public Task ExecuteAsync(ForgotPasswordJobData jobData)
{
// Do some work
return Task.CompletedTask;
}
}现在我想用ExecuteAsync方法来装饰
[AutomaticRetry(Attempts = 5)]但是,我不想把它放在应用层中,因为这将创建对基础结构层的依赖。AutomaticRetry是位于基础设施层的hangfire库的一个特性。
有没有一种在应用层中抽象[AutomaticRetry(Attempts = 5)]的方法?
发布于 2021-12-13 11:39:14
这句话让我走上了正确的道路:
,我将使用带有被动属性的JobFilter。请参阅ServerFilterProvider.GetFilters方法中的stackoverflow.com.com/a/57396553/1236044,您应该“只需要”搜索job.Method.GetCustomAttributes以寻找您自己的被动MyAutomaticRetry属性。取决于您是否找到一个,您将返回一个JobFilter,其中包含一个Hangfire.AutomaticRetryAttribute。抱歉错过了一个正确的答案
在应用层中定义自定义属性:
[AttributeUsage(AttributeTargets.Method)]
public class JobRetryAttribute : Attribute
{
public int Attempts;
public bool DeleteOnAttemptsExceeded;
public JobRetryAttribute(int Attempts, bool DeleteOnAttemptsExceeded)
{
this.Attempts = Attempts;
this.DeleteOnAttemptsExceeded = DeleteOnAttemptsExceeded;
}
}创建挂火作业筛选器提供程序:
public class ServerFilterProvider : IJobFilterProvider
{
public IEnumerable<JobFilter> GetFilters(Job job)
{
var attribute = job.Method
.GetCustomAttributesData()
.Where(a => a.AttributeType == typeof(JobRetryAttribute))
.Select(a => new AutomaticRetryAttribute
{
Attempts = Convert.ToInt32(a.ConstructorArguments.First().Value),
OnAttemptsExceeded = Convert.ToBoolean(a.ConstructorArguments.Skip(1).First().Value) ? AttemptsExceededAction.Delete : AttemptsExceededAction.Fail
})
.First();
if (attribute != null)
{
return new JobFilter[] { new JobFilter(attribute, JobFilterScope.Method, null) };
}
return Enumerable.Empty<JobFilter>();
}
}使用它:
JobFilterProviders.Providers.Add(new ServerFilterProvider());发布于 2021-12-10 17:11:42
如果使用Interface,则属性将不会继承到实现中。
但是如果使用抽象类,它将继承
public interface IJobData
{ }
public abstract class MyJob<TJobData> where TJobData : IJobData
{
[AutomaticRetry(Attempts = 5)]
public abstract Task ExecuteAsync(TJobData jobData);
}https://stackoverflow.com/questions/70306976
复制相似问题