当前访客身份:游客 [ 登录 | 加入开源中国 ]

代码分享

当前位置:
代码分享 » C#  » 常用工具方法
分享到: 
收藏 +0
3
默认的TypeResolver (见 http://www.oschina.net/code/snippet_871522_15682),每次解析时都会创建一个新的对象. 这里做一个简单的扩展,单件方式,解析倚赖.

代码片段(2) [全屏查看所有代码]

1. [代码]单件解析的测试(功能描述): 第一次解析使用Actual_resolver,第二次用存好的.     跳至 [1] [2] [全屏预览]

using Machine.Specifications;
using Machine.Specifications.AutoMocking.Rhino;
using Rhino.Mocks;
using Skight.eLiteWeb.Domain.Containers;

namespace Skight.eLiteWeb.Domain.Specs.Containers
{
    public class SingletonResolverSpecs : Specification<DiscreteItemResolver, SingletonResolver>
    {
        private Establish context =
          () => DependencyOf<DiscreteItemResolver>().Stub(x => x.resolve())
                                                    .Return(new object());
    }
    public class when_first_time_call_singleton_to_resolve : SingletonResolverSpecs
    {

        private Because of =
            () => result = subject.resolve();

        private It should_call_actual_resolver = 
            ()=> DependencyOf<DiscreteItemResolver>().AssertWasCalled(x => x.resolve());

        private It should_resolve_an_object =
            () => result.ShouldNotBeNull();

        private static object result;
    }

    public class when_two_time_call_singleton_to_resolve : SingletonResolverSpecs
    {
        
        private Because of =
            () => { 
                result1 = subject.resolve();
                result2 = subject.resolve();
            };

        private It should_call_actual_resolver =
            () => DependencyOf<DiscreteItemResolver>().AssertWasCalled(x => x.resolve(),opt=>opt.Repeat.Once());

        private It should_resolve_same_result =
            () => result1.ShouldBeTheSameAs(result2);
        private static object result1;
        private static object result2;
    }
}

2. [代码]单件解析的实现: Decorator     跳至 [1] [2] [全屏预览]

namespace Skight.eLiteWeb.Domain.Containers
{
    public class SingletonResolver:DiscreteItemResolver
    {
        private readonly DiscreteItemResolver actual_resolver;
        private object result;

        public SingletonResolver(DiscreteItemResolver actualResolver)
        {
            actual_resolver = actualResolver;
        }

        public object resolve()
        {
            return result ?? (result = actual_resolver.resolve());
        }
    }
}


开源中国-程序员在线工具:Git代码托管 API文档大全(120+) JS在线编辑演示 二维码 更多»