你什么时候需要SimpleInjector混合注册? (怎样才能在IIS托管对象被称为没有一个H

2019-10-17 16:36发布

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?

Answer 1:

如史蒂芬评价已概述的,通常需要混合注册当Web请求可以在另一个线程上启动一个进程。 在这种情况下,可以将容器需要两个Web请求和线程的请求的服务请求。



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