代码之家  ›  专栏  ›  技术社区  ›  Paul

在构造函数中使用httpContextBase时出现结构映射错误

  •  1
  • Paul  · 技术社区  · 15 年前

    我正在.NET 4.0上构建一个ASP.NET MVC 2.0应用程序,并正在为IOC使用StructureMap 2.6.1。我最近添加了一个i cookie和cookie类,cookie类将httpContextBase作为构造函数参数(见下文),现在当我运行我的应用程序时,我得到了这个错误:没有为pluginFamily system.web.httpContextBase定义默认实例。

    我以前在另一个具有相同堆栈的MVC应用程序中使用过这个方法,但没有得到这个错误。我错过什么了吗?如果我需要在我的结构映射配置文件中为httoContextBase添加一些映射代码,我将使用什么?

    帮助会很好!!!!

    曲奇.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 回复  |  直到 15 年前
        1
  •  10
  •   Joshua Flanagan    15 年前

    我相信您需要根据begin_请求处理程序中的每个请求注册httpContextBase,如下所示:

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

    更新:确保注册了lambda,否则结构映射将把注册时可用的httpContext存储为singleton。