在构造函数中使用HttpContextBase时出现Structuremap错误

时间:2010-09-23 02:03:25

标签: asp.net asp.net-mvc-2 .net-4.0 structuremap

我正在.NET 4.0上构建一个ASP.NET MVC 2.0应用程序,并且正在使用Structuremap 2.6.1 for IoC。我最近添加了一个ICookie和Cookie类,Cookie类将HttpContextBase作为构造函数参数(见下文),现在当我运行我的应用程序时,我收到此错误:没有为PluginFamily System.Web.HttpContextBase定义默认实例。

我之前在另一个具有相同堆栈的MVC应用程序中使用过此方法,但没有收到此错误。我错过了什么吗?如果我确实需要在我的structuremap配置文件中为HttoContextBase添加一些映射代码,我会使用什么?

帮助会很棒!!!

Cookie.cs

public class Cookie : ICookie
{
    private readonly HttpContextBase _httpContext;
    private static bool defaultHttpOnly = true;
    private static float defaultExpireDurationInDays = 1;
    private readonly ICryptographer _cryptographer;
    public Cookie(HttpContextBase httpContext, ICryptographer cryptographer)
    {
        Check.Argument.IsNotNull(httpContext, "httpContext");
        Check.Argument.IsNotNull(cryptographer, "cryptographer");
        _cryptographer = cryptographer;
        _httpContext = httpContext;
    }
    public static bool DefaultHttpOnly
    {
        [DebuggerStepThrough]
        get { return defaultHttpOnly; }

        [DebuggerStepThrough]
        set { defaultHttpOnly = value; }
    }

    public static float DefaultExpireDurationInDays
    {
        [DebuggerStepThrough]
        get { return defaultExpireDurationInDays; }

        [DebuggerStepThrough]
        set
        {
            Check.Argument.IsNotZeroOrNegative(value, "value");
            defaultExpireDurationInDays = value;
        }
    }

    public T GetValue<T>(string key)
    {
        return GetValue<T>(key, false);
    }

    public T GetValue<T>(string key, bool expireOnceRead)
    {
        var cookie = _httpContext.Request.Cookies[key];
        T value = default(T);
        if (cookie != null)
        {
            if (!string.IsNullOrWhiteSpace(cookie.Value))
            {
                var converter = TypeDescriptor.GetConverter(typeof(T));
                try
                {
                    value = (T)converter.ConvertFromString(_cryptographer.Decrypt(cookie.Value));
                }
                catch (NotSupportedException)
                {
                    if (converter.CanConvertFrom(typeof(string)))
                    {
                        value = (T)converter.ConvertFrom(_cryptographer.Decrypt(cookie.Value));
                    }
                }
            }
            if (expireOnceRead)
            {
                cookie = _httpContext.Response.Cookies[key];

                if (cookie != null)
                {
                    cookie.Expires = DateTime.Now.AddDays(-100d);
                }
            }
        }
        return value;
    }

    public void SetValue<T>(string key, T value)
    {
        SetValue(key, value, DefaultExpireDurationInDays, DefaultHttpOnly);
    }

    public void SetValue<T>(string key, T value, float expireDurationInDays)
    {
        SetValue(key, value, expireDurationInDays, DefaultHttpOnly);
    }

    public void SetValue<T>(string key, T value, bool httpOnly)
    {
        SetValue(key, value, DefaultExpireDurationInDays, httpOnly);
    }

    public void SetValue<T>(string key, T value, float expireDurationInDays, bool httpOnly)
    {
        TypeConverter converter = TypeDescriptor.GetConverter(typeof(T));
        string cookieValue = string.Empty;
        try
        {
            cookieValue = converter.ConvertToString(value);
        }
        catch (NotSupportedException)
        {
            if (converter.CanConvertTo(typeof(string)))
            {
                cookieValue = (string)converter.ConvertTo(value, typeof(string));
            }
        }
        if (!string.IsNullOrWhiteSpace(cookieValue))
        {
            var cookie = new HttpCookie(key, _cryptographer.Encrypt(cookieValue))
            {
                Expires = DateTime.Now.AddDays(expireDurationInDays),
                HttpOnly = httpOnly
            };
            _httpContext.Response.Cookies.Add(cookie);
        }
    }
}

IocMapping.cs

public class IoCMapping
{
    public static void Configure()
    {

        var connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ProjectName.Core.Properties.Settings.ProjectNameConnectionString"].ConnectionString;
        MappingSource mappingSource = new AttributeMappingSource();
        ObjectFactory.Initialize(x =>
        {
            x.Scan(scan =>
            {
                scan.Assembly("ProjectName.Core");
                scan.Assembly("ProjectName.WebUI");
                scan.WithDefaultConventions();
            });
            x.For<IUnitOfWork>().HttpContextScoped().Use<UnitOfWork>();
            x.For<IDatabase>().HttpContextScoped().Use<Database>().Ctor<string>("connection").Is(connectionString).Ctor<MappingSource>("mappingSource").Is(mappingSource);
            x.For<ILogger>().Singleton().Use<NLogLogger>();
            x.For<ICacheManager>().Singleton().Use<CacheManager>().Ctor<System.Web.Caching.Cache>().Is(HttpRuntime.Cache);
            x.For<IEmailSender>().Singleton().Use<EmailSender>();
            x.For<IAuthenticationService>().HttpContextScoped().Use<AuthenticationService>();
            x.For<ICryptographer>().Use<Cryptographer>();
            x.For<IUserSession>().HttpContextScoped().Use<UserSession>();
            x.For<ICookie>().HttpContextScoped().Use<Cookie>();
            x.For<ISEORepository>().HttpContextScoped().Use<SEORepository>(); 
            x.For<ISpotlightRepository>().HttpContextScoped().Use<SpotlightRepository>(); 
            x.For<IContentBlockRepository>().HttpContextScoped().Use<ContentBlockRepository>();
            x.For<ICatalogRepository>().HttpContextScoped().Use<CatalogRepository>();
            x.For<IPressRoomRepository>().HttpContextScoped().Use<PressRoomRepository>();
            x.For<IEventRepository>().HttpContextScoped().Use<EventRepository>();
            x.For<IProductRegistrationRepository>().HttpContextScoped().Use<ProductRegistrationRepository>();
            x.For<IWarrantyRepository>().HttpContextScoped().Use<WarrantyRepository>();
            x.For<IInstallerRepository>().HttpContextScoped().Use<InstallerRepository>();
            x.For<ISafetyNoticeRepository>().HttpContextScoped().Use<SafetyNoticeRepository>();
            x.For<ITradeAlertRepository>().HttpContextScoped().Use<TradeAlertRepository>();
            x.For<ITestimonialRepository>().HttpContextScoped().Use<TestimonialRespository>();
            x.For<IProjectPricingRequestRepository>().HttpContextScoped().Use<ProjectPricingRequestRepository>();
            x.For<IUserRepository>().HttpContextScoped().Use<UserRepository>();
            x.For<IRecipeRepository>().HttpContextScoped().Use<RecipeRepository>();
        });

        LogUtility.Log.Info("Registering types with StructureMap");
    }
}

1 个答案:

答案 0 :(得分:10)

我相信您需要在Begin_Request处理程序中的每个请求上注册HttpContextBase,如下所示:

For<HttpContextBase>().Use(() => new HttpContextWrapper(HttpContext.Current));

更新:确保注册lambda,否则StructureMap会将注册时可用的HttpContext存储为单例。