新建一个空的Web项目AspnetBootstrappingDemo

然后添加NuGet组件

  • Nancy

  • Nancy.Hosting.Aspnet

  • Nancy.ViewEngines.Razor

继续往项目里面添加Module,Views,Models文件夹,然而先写Models文件夹里面的类,往Models文件夹添加 RatPack类

 public string FirstName { get; set; }

再往Models文件夹里面添加RatPackWithDependencyText类,并让它继承RatPack

 public string ApplicationDependencyText { get; set; }        public string RequestDependencyText { get; set; }

再往Models文件夹里添加IApplicationDependency类

 string GetContent();

再往Models文件夹里面添加IRequestDependency类

 string GetContent();

再往Models文件夹里面添加ApplicationDependency类

private readonly DateTime currentDateTime;        /// 
        /// 初始化 RequestDependencyClass 类的新实例        /// 
        public ApplicationDependency()
        {            this.currentDateTime = DateTime.Now;
        }        public string GetContent()
        {            return "这是一个应用程序级依赖项, 构建在:" + this.currentDateTime.ToLongTimeString();
        }

继续往Models文件夹里面添加RequestDependency类

 private readonly DateTime currentDateTime;        /// 
        /// 初始化 RequestDependency 类的新实例        /// 
        public RequestDependency()
        {            this.currentDateTime = DateTime.Now;
        }        public string GetContent()
        {            return "这是按请求的依赖项, 构造于:" + this.currentDateTime.ToLongTimeString();
        }

然后往Module文件夹里面添加DependencyModule类

private readonly IApplicationDependency applicationDependency;        private readonly IRequestDependency requestDependency;        public DependencyModule(IApplicationDependency applicationDependency,IRequestDependency requestDependency)
        {            this.applicationDependency = applicationDependency;            this.requestDependency = requestDependency;
            Get("/",Lexan=>
            {                var model = new RatPackWithDependencyText
                {
                    FirstName="Lexan",
                    ApplicationDependencyText=this.applicationDependency.GetContent(),
                    RequestDependencyText=this.requestDependency.GetContent()
                };                return View["razor-dependency",model];
            });
        }

继续往根目录下添加Bootstrapper类

 protected override void ConfigureApplicationContainer(TinyIoCContainer container)
        {            //base.ConfigureApplicationContainer(container);            //将应用程序依赖项注册为普通的单一实例
            container.Register().AsSingleton();            //将每个请求的依赖项注册为每个请求的单一实例
            container.Register().AsPerRequestSingleton();
        }

然后往Views文件夹里面添加razor-dependency页面





    
    剃刀视图引擎Demo


    
    

你好,@Model.FirstName

        

这是一个剃刀的页面

        

@Model.ApplicationDependencyText

        

@Model.RequestDependencyText

    

最后修改Web.config文件

      
      
    
  
    
    
    
    
      
    
  

运行看看界面如何