新建一个空的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; /// <summary> /// 初始化 RequestDependencyClass 类的新实例 /// </summary> public ApplicationDependency() { this.currentDateTime = DateTime.Now; } public string GetContent() { return "这是一个应用程序级依赖项, 构建在:" + this.currentDateTime.ToLongTimeString(); }
继续往Models文件夹里面添加RequestDependency类
private readonly DateTime currentDateTime; /// <summary> /// 初始化 RequestDependency 类的新实例 /// </summary> 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<IApplicationDependency,ApplicationDependency>().AsSingleton(); //将每个请求的依赖项注册为每个请求的单一实例 container.Register<IRequestDependency,RequestDependency>().AsPerRequestSingleton(); }
然后往Views文件夹里面添加razor-dependency页面
<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>剃刀视图引擎Demo</title> </head> <body> <div> <h1>你好,@Model.FirstName</h1> <p>这是一个剃刀的页面</p> <p>@Model.ApplicationDependencyText</p> <p>@Model.RequestDependencyText</p> </div> </body> </html>
最后修改Web.config文件
<httpHandlers> <add verb="*" type="Nancy.Hosting.Aspnet.NancyHttpRequestHandler" path="*" /> </httpHandlers> </system.web> <system.webServer> <modules runAllManagedModulesForAllRequests="true" /> <validation validateIntegratedModeConfiguration="false" /> <handlers> <add name="Nancy" verb="*" type="Nancy.Hosting.Aspnet.NancyHttpRequestHandler" path="*" /> </handlers> </system.webServer>
运行看看界面如何
本文转自 sshpp 51CTO博客,原文链接:http://blog.51cto.com/12902932/1926510,如需转载请自行联系原作者