你什么时候需要SimpleInjector混合注册? (如何在没有HttpContext的情况下调用IIS中托管的对象?) [英] When would you need SimpleInjector hybrid registration? (How can an object hosted in IIS be called without a HttpContext?)

查看:132
本文介绍了你什么时候需要SimpleInjector混合注册? (如何在没有HttpContext的情况下调用IIS中托管的对象?)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

继续我最近关于SimpleInjector和混合网络请求/线程生活方式的问题似乎我并不完全理解技术要求并且做了一些我实际上不需要做的事情。

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.

使用此代码

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;
});

我的理解是,对于在IIS中运行的AppDomains, IWebUnitOfWork ,否则会出现错误,除非我已明确声明LifetimeScope的实例来包装对容器的调用(将返回 IThreadUnitOfWork ) 。

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!


然而,你似乎并不需要混合生活方式。混合生活方式是一种可以动态切换的生活方式(每次调用GetInstance和每次注射时),而您似乎只需要在启动时切换。

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.

我的问题是:在什么情况下,在IIS内运行的AppDomain中加载的容器(或任何其他类),无论是静态还是实例,都可以在没有存在的情况下调用一个HttpContext?

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?

推荐答案

正如Steven在评论中所概述的那样,当Web请求可以启动一个进程时,通常需要混合注册在另一个线程上。在这种情况下,可以要求容器为Web请求和线程请求提供服务请求。

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.

这篇关于你什么时候需要SimpleInjector混合注册? (如何在没有HttpContext的情况下调用IIS中托管的对象?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆