日期:2014-05-17  浏览次数:20982 次

依赖注入框架的C#实现(连载中)--之一兵马未动,测试先行。
本帖最后由 hWonner 于 2012-07-31 05:42:26 编辑
第一个版本,兵马未动,测试先行。
完整代码

先模拟要注入的代码: Service和Repository

 public interface StubService
    {
        StubRepository Repository { get; } 
    }

    public class StubServiceImpl : StubService
    {
        private StubRepository repository;

        public StubServiceImpl(StubRepository repository)
        {
            this.repository = repository;
        }

        public StubRepository Repository
        {
            get { return repository; }
        }
    }
    public interface StubRepository
    {
        
    }
    public class StubRepositoryImpl:StubRepository
    {
        
    }


测试,如何注入:

 public class DependencyIntegrationSpecs
    {
        private Because of =
            () => service = Container.get<StubService>();

        private It should_inject_repository_into_service =
            () => service.Repository.ShouldBeOfType<StubRepositoryImpl>();

        private It inject_repository_should_not_be_null =
            () => service.Repository.ShouldNotBeNull();
             
        private static StubService service;
    }

------解决方案--------------------
是否,代码未动,测试先行。
------解决方案--------------------
依赖注入的典型应用场景之一。
------解决方案--------------------
代码未动,测试先行。
------解决方案--------------------
不错,看了半天才明白... ...
先从Container.get<StubService>()获取StubService接口实例,
然后通过service.Repository.ShouldBeOfType<StubRepositoryImpl>()获取StubService接口下的StubRepositoryImpl这个实现类... ...
不知道理解的对不对... ..
不过建议楼主代码再规范一点,更好,本文可以作为IOC的入门教科书了... ...
------解决方案--------------------
不懂。。
------解决方案--------------------
这里也来喷一下,你要给代码就应该给出完整的测试代码,看看你的测试部分,那么多自定义类型没给出,也没有代码注释,这是在炫耀代码还是什么?没有半点说明的代码没半点价值(即使是英文说明也是说明)。