我有一系列用于处理WebJobs的类,看起来像这样:
public class EnvelopeSalutationJob : BatchJob
{
public EnvelopeSalutationJob( StringWriter swLogger )
: base( swLogger, "Envelope Salutation Job" )
{
}
[ Singleton() ]
public async Task ProcessMessage(
[ QueueTrigger( "%" + nameof( ContainerQueueConstants.EnvelopeSalutation ) + "%" ) ] EnvelopeSalutationMessage msg,
TextWriter azureLogWriter
)
{
PhaseNames.SetNames( "Processing Homes", "Job Completed" );
await ExecuteFromMessage( msg, azureLogWriter, Launch );
}
}
这些使用AutoFac作为DI框架非常有效,配置如下:
public static class ContainerConfig
{
public static IContainer GetContainer()
{
var builder = new ContainerBuilder();
// per job
builder.RegisterType<StringWriter>();
// jobs
builder.RegisterType<EnvelopeSalutationJob>();
return builder.Build();
}
}
但最近我想把这些工作“泛化”,以便它们与特定的DbContexts无关。我尝试使用这样的模式:
public class EnvelopeSalutationJob<TContext, TUser>
: BatchJob<TContext, TUser>
where TContext : IdentityDbContext<TUser>, ICampaignContext, new()
where TUser : IdentityUser, INamedUser
{
public EnvelopeSalutationJob( StringWriter swLogger )
: base( swLogger, "Envelope Salutation Job" )
{
}
[ Singleton() ]
public async Task ProcessMessage(
[ QueueTrigger( "%" + nameof( ContainerQueueConstants.EnvelopeSalutation ) + "%" ) ] EnvelopeSalutationMessage msg,
TextWriter azureLogWriter
)
{
PhaseNames.SetNames( "Processing Homes", "Job Completed" );
await ExecuteFromMessage( msg, azureLogWriter, Launch );
}
}
AutoFac配置更改为:
public static class ContainerConfig
{
public static IContainer GetContainer()
{
var builder = new ContainerBuilder();
// per job
builder.RegisterType<StringWriter>();
// jobs
builder.RegisterType<EnvelopeSalutationJob<ConnellJobContext, ConnellUser>>();
return builder.Build();
}
}
不幸的是,这不起作用。 WebJobs控制台应用程序启动正常,但它抱怨:
找不到工作职能。尝试制作你的工作类和方法 公共
是否无法将作业绑定到泛型类的实例?
答案 0 :(得分:2)
根据您的描述,我已经测试了这个问题,我可以按如下方式重现此问题:
在我检查了git上的Azure WebJobs SDK源代码后,我发现DefaultTypeLocator.cs会使用调用Type.ContainsGenericParameters的IsJobClass
来过滤类型,如下所示:
public static bool IsJobClass(Type type)
{
if (type == null)
{
return false;
}
return type.IsClass
// For C# static keyword classes, IsAbstract and IsSealed both return true. Include C# static keyword
// classes but not C# abstract keyword classes.
&& (!type.IsAbstract || type.IsSealed)
// We only consider public top-level classes as job classes. IsPublic returns false for nested classes,
// regardless of visibility modifiers.
&& type.IsPublic
&& !type.ContainsGenericParameters;
}
此外,FunctionIndexer.cs会使用IsJobMethod
过滤方法,如下所示:
public bool IsJobMethod(MethodInfo method)
{
if (method.ContainsGenericParameters)
{
return false;
}
if (method.GetCustomAttributesData().Any(HasJobAttribute))
{
return true;
}
if (method.GetParameters().Length == 0)
{
return false;
}
if (method.GetParameters().Any(p => p.GetCustomAttributesData().Any(HasJobAttribute)))
{
return true;
}
return false;
}
根据我的理解,Azure WebJobs SDK不支持您将作业绑定到当前通用类的实例。您可以定义BaseDbContext
并利用构造函数依赖注入来初始化DbContext
实例。另外,您可以添加反馈here。