1

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();
}
Dorin
  • 2,482
  • 2
  • 22
  • 38
  • 1
    There is a lifecycle called `HybridHttpOrThreadLocalScoped` that will fall back to per thread caching if a `HttpContext` is not available. – PHeiberg Nov 16 '12 at 08:12
  • Running background threads inside an asp.net application is usually not a good plan. – Damien_The_Unbeliever Nov 16 '12 at 08:22
  • @Damien_The_Unbeliever I am well informed about the downsides of running background threads inside asp.net application. Thanks – Dorin Nov 16 '12 at 08:24

1 Answers1

2

Try:

ObjectFactory.Initialize(x =>
{
    x.For<DbEntities>().HybridHttpOrThreadLocalScoped().Use(CreateNewDbEntities); 
}

This should cache the instance per thread if a HttpContext is not available.

PHeiberg
  • 29,411
  • 6
  • 59
  • 81
  • For `HttpContextScoped` instances, I run `ObjectFactory.ReleaseAndDisposeAllHttpScopedObjects()` in `Global.asax`'s `Application_EndRequest` method. Is there something similar in this case? Or should the task itself take care of that? – marapet Nov 16 '12 at 08:36
  • I didn't know how to do it before, but I managed to find a question about it [here](http://stackoverflow.com/questions/6424629/how-to-release-hybridhttporthreadlocalscoped-objects-in-structuremap). Basicly it comes down to `new HybridLifecycle().FindCache().DisposeAndClear();` – PHeiberg Nov 16 '12 at 08:54