I am using StructureMap for creating instance of DbEntities per request in ASP.NET.
ObjectFactory.Initialize(x =>
{
x.For<DbEntities>().HttpContextScoped().Use(CreateNewDbEntities);
}
I have a bacgkround task running every 5 seconds which is trying to use DbEntities.
timer = new Timer(RunTasks, null, 1000 * 10/*time to wait until the first run*/, 1000 * 5/*time to wait between calls*/);
Now in method RunTasks I get null reference excption when I try to call GetDbEntities
private static void RunTasks(object sender)
{
var muninService = GetDbEntities(); // Null reference excpetion
}
public static DbEntities GetDbEntities()
{
return ObjectFactory.GetInstance<DbEntities>();
}
I am guessing this is becauase in a background thread I don't have access to httpcontextscope. Now I am new to structure map and I don't know were to start and fix this problem. Any ideas ?
Other methods that I use:
private static DbEntities CreateNewDbEntities()
{
return new DbEntities();
}