Following on from my recent question regarding SimpleInjector and hybrid web request/thread lifestyles it seems I do not fully understand the technical requirements and have been doing something I don't actually need to do.
With this code
interface IUnitOfWork { }
interface IWebUnitOfWork : IUnitOfWork { }
interface IThreadUnitOfWork : IUnitOfWork { }
class UnitOfWork : IWebUnitOfWork, IThreadUnitOfWork { }
container.RegisterPerWebRequest<IWebUnitOfWork, UnitOfWork>();
container.RegisterLifetimeScope<IThreadUnitOfWork, UnitOfWork>();
container.Register<IUnitOfWork>(() => container.GetInstance<UnitOfWork>());
// Register as hybrid PerWebRequest / PerLifetimeScope.
container.Register<UnitOfWork>(() =>
{
if (HttpContext.Current != null)
return container.GetInstance<IWebUnitOfWork>() as UnitOfWork;
else
return container.GetInstance<IThreadUnitOfWork>() as UnitOfWork;
});
My understanding was that for AppDomains running within IIS the IWebUnitOfWork
would be returned, and otherwise there would be an error unless I have explicitly declared an instance of a LifetimeScope to wrap the call to the container (which would return IThreadUnitOfWork
).
The following statement has made me realise I don't fully understand what I've been doing!
You however, don't seem to need a hybrid lifestyle add all. A hybrid lifestyle is a lifestyle that can switch dynamically (on each call to GetInstance and per each injection), while you only seem to need to switch during start-up.
My question is this: under what circumstances can a container (or any other class for that matter), be it static or instance, that is loaded within an AppDomain running within IIS, be called without the existence of a HttpContext?