StructureMap:如何向方法提供System.Web.HttpRequestBase?

时间:2011-03-02 14:20:12

标签: c# structuremap ioc-container

我正在尝试为Cookie实现一个包装器,如下所示:

http://chwe.at/blog/post/2009/01/28/Testable-and-reusable-cookie-access-with-ASPNet-MVC-RC.aspx

但是StructureMap失败并出现错误:

StructureMap Exception Code:  202
No Default Instance defined for PluginFamily System.Web.HttpRequestBase,
System.Web.Abstractions, Version=3.5.0.0, Culture=neutral,     
PublicKeyToken=31bf3856ad364e35

我认为这是因为我试图让StructureMap为以下方法提供参数:

    public CookieContainer(HttpRequestBase request, HttpResponseBase response)
    {
        Check.IsNotNull(request, "request");
        Check.IsNotNull(response, "response");

        _request = request;
        _response = response;
    }

我尝试将以下内容添加到StructureMap注册表中:

        ForRequestedType<HttpRequestBase>()
            .TheDefaultIsConcreteType<HttpRequestBase>();

        ForRequestedType<HttpResponseBase>()
            .TheDefaultIsConcreteType<HttpResponseBase>();

但是失败并出现错误:

StructureMap Exception Code:  180
StructureMap cannot construct objects of Class System.Web.HttpRequestBase, 
System.Web.Abstractions, Version=3.5.0.0, Culture=neutral,
PublicKeyToken=31bf3856ad364e35 because there is no public constructor found. 

如何让StructureMap向方法提供HttpRequestBaseHttpResponseBase个对象?

2 个答案:

答案 0 :(得分:3)

这是因为HttpRequestBase是抽象的,而SM对此无能为力。

使用出厂的Methode

ForRequestedType<HttpRequestBase>().TheDefault.Is
  .ConstructedBy(() => HttpContext.Request);

答案 1 :(得分:0)

事实证明我不需要重载的构造函数..所以我所要做的就是删除它:

public CookieContainer(HttpRequestBase request, HttpResponseBase response)
{
    Check.IsNotNull(request, "request");
    Check.IsNotNull(response, "response");

    _request = request;
    _response = response;
}

此构造函数仅用于创建模拟cookie容器,您可以在其中传递模拟HttpRequestBaseHttpResponseBase对象。