I have multiple background Batch jobs to Run and I have been asked to have single webJob to run all task, which I need to schedule to run at different time.
I have used Timer feature from webJob.Extensions.
i.e in the Program.cs
var config = new JobHostConfiguration
{
JobActivator = new AutofacActivator(ContainerConfig<Functions>.GetContainer())
};
if (config.IsDevelopment)
{
config.UseDevelopmentSettings();
}
config.UseTimers();
var host = new JobHost(config);
host.RunAndBlock();
And the function will have multiple method and are triggered in interval of 30 min.
public void ProcessMethod1([TimerTrigger("0 0/30 * * * *")] TimerInfo timer)
{
//Logic
}
public void ProcessMethod2([TimerTrigger("0 0/30 * * * *")] TimerInfo timer)
{
//Logic
}
Issue: Since I am using Autofac DI. I am creating the instance for dbContext at the start of the Job
JobActivator = new AutofacActivator(ContainerConfig<Functions>.GetContainer())
While executing the webJob I am getting errors while executing DB select like "An attempt was made to use the context while it is being configured".
Since I gave scope as InstancePerLifetimeScope(). I want to know if the Two operation will get same instance?
Also for Logging I have similar issue, since it looks like only one instance is created for these two different Operation.
All I want is to have separate instance for both DBCOntext and Logger based on operation. Pls advise me how I can set DI for this scenario.
Update:
public class AutofacActivator: IJobActivator
{
private readonly Autofac.IContainer _container;
public AutofacActivator(Autofac.IContainer container)
{
_container = container;
}
public T CreateInstance<T>()
{
return _container.Resolve<T>();
}
}
internal class WebJobIocModule<T> : Autofac.Module
{
protected override void Load(ContainerBuilder builder)
{
if (builder == null)
throw new ArgumentNullException("WebJobBuilder");
//Cascade
builder.RegisterModule(new BusinessObjectIocModule());
// Register the functions class - WebJobs will discover our triggers this way
builder.RegisterType<T>();
}
}
public class BusinessObjectIocModule :Autofac.Module
{
protected override void Load(ContainerBuilder builder)
{
if(builder == null) throw new ArgumentNullException("BusinessObjectBuilder");
//Cascade
builder.RegisterModule(new DataAccessRepoIocModule());
builder.RegisterType<BusinessObjBpc>().AsImplementedInterfaces();
}
}
In DataAccessIOC:
string connectionString = ConfigurationManager.ConnectionStrings["DBConnectionAppKeyName"].ConnectionString;
optionsStagingBuilder.UseSqlServer(connectionString);
builder.RegisterType<DataAccessDbContext>()
.AsSelf()
.WithParameter("options", optionsStagingBuilder.Options)
.InstancePerLifetimeScope();