如何在Unity中实现这个(HttpContext)依赖?
我们有一个依赖于 HttpContext
的类。 我们是这样实现的:
public SiteVariation() : this(new HttpContextWrapper(HttpContext.Current))
{
}
public SiteVariation(HttpContextBase context)
{}
现在我想做的是通过 Unity
实例化 SiteVariation
类,这样我们就可以创建一个构造函数。 但我不知道如何在Unity中以配置方式配置这个新的HttpContextWrapper(HttpContext.Current))
。
附注 这是我们使用的配置方式
<type type="Web.SaveRequest.ISaveRequestHelper, Common" mapTo="Web.SaveRequest.SaveRequestHelper, Common" />
we have a class with a dependency to the HttpContext
.
We've implemented it like this:
public SiteVariation() : this(new HttpContextWrapper(HttpContext.Current))
{
}
public SiteVariation(HttpContextBase context)
{}
Now what i want to do is to instantiate the SiteVariation
class via Unity
, so we can create one constructor.
But i do not know how to configure this new HttpContextWrapper(HttpContext.Current))
in Unity in the config way.
ps
this is the config way we use
<type type="Web.SaveRequest.ISaveRequestHelper, Common" mapTo="Web.SaveRequest.SaveRequestHelper, Common" />
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Microsoft 已经围绕 .NET 中包含的
HttpContext
、HttpRequest
和HttpResponse
构建了出色的包装器和抽象,因此我肯定会直接使用它们,而不是直接使用它们我自己包裹它。您可以使用
InjectionFactory
为HttpContextBase
配置 Unity,如下所示:此外,如果您需要
HttpRequestBase
(我最常使用它)并且HttpResponseBase
,您可以像这样注册它们:您可以在单元测试中轻松模拟
HttpContextBase
、HttpRequestBase
和HttpResponseBase
,而无需定制包装。Microsoft has already built great wrappers and abstractions around
HttpContext
,HttpRequest
andHttpResponse
that is included in .NET so I would definitely use those directly rather than wrapping it myself.You can configure Unity for
HttpContextBase
by usingInjectionFactory
, like this:Additionally, if you need
HttpRequestBase
(which I tend to use the most) andHttpResponseBase
, you can register them like this:You can easily mock
HttpContextBase
,HttpRequestBase
andHttpResponseBase
in unit tests without custom wrappers.我不会直接依赖
HttpContextBase
。相反,我会在它周围创建一个包装器,并使用您需要的位:然后是实现:
这样,您的类现在只依赖于包装器,并且不需要实际的 HttpContext 来运行。使得注入更容易,测试也更容易:
I wouldn't take a dependency on
HttpContextBase
directly. I would instead create a wrapper around it, and use the bits you need:then the implementation:
This way, your class now just relies on a wrapper, and doesn't need the actual HttpContext to function. Makes it much easier to inject, and much easier to test: