When would you need SimpleInjector hybrid registration? (How can an object hosted in IIS be called without a HttpContext?)

我们两清 提交于 2020-01-16 02:05:43

问题


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?


回答1:


As Steven has outlined in the comments, hybrid registration is generally needed when a web request can start a process on another thread. In this situation the container can be required to service requests for both Web Requests and Thread requests.



来源:https://stackoverflow.com/questions/14693774/when-would-you-need-simpleinjector-hybrid-registration-how-can-an-object-hoste

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!