Testing Castle windsor Component with PerWebRequest lifestyle

后端 未结 4 2018
夕颜
夕颜 2020-12-31 02:00

I\'m trying to do some testing with castle windsor involved, in one of my tests I want to check the windsor installers, so I check that the container can resolve my componen

4条回答
  •  甜味超标
    2020-12-31 02:37

    I ended up implementing this extension. ATTN: Must call before loading components with the PerWebRequest lifestyle:

    public static class WindsorContainerExtensions
    {
        public static IWindsorContainer OverridePerWebRequestLifestyle(this IWindsorContainer container)
        {
            container.Kernel.ComponentModelCreated += model =>
            {
                if (model.IsPerWebRequestLifestyle())
                {
                    model.LifestyleType = LifestyleType.Transient;
                }
            };
    
            return container;
        }
    
        private static bool IsPerWebRequestLifestyle(this ComponentModel model)
        {
            return model.LifestyleType == LifestyleType.Scoped
                && model.HasAccessorType(typeof(WebRequestScopeAccessor));
        }
    
        private static bool HasAccessorType(this ComponentModel model, Type type)
            => model.HasExtendedProperty("castle.scope-accessor-type", type);
    
        private static bool HasExtendedProperty(this ComponentModel model, object key, T expected)
        {
            return model.ExtendedProperties[key] is T actual
                && EqualityComparer.Default.Equals(actual, expected);
        }
    }
    

    Requires these imports:

    using System;
    using System.Collections.Generic;
    using Castle.Core;
    using Castle.Facilities.AspNet.SystemWeb;
    using Castle.Windsor;
    

提交回复
热议问题