ASP.NET MVC SportStore 购物网示例(2)

连接数据库

创建SportStore数据库。

clip_image001clip_image003

创建表 Products

clip_image004

添加一些演示数据:

clip_image005

设置Linq to SQL

注意:需要引用 System.Data.Linq。

[Table(Name="Products")]

public class Product

{

[Column(IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.OnInsert)]

public int ProductID { get; set; }

[Column]

public string Name { get; set; }

[Column]

public string Description { get; set; }

[Column]

public decimal Price { get; set; }

[Column]

public string Category { get; set; }

}

创建一个真实的响应

namespace DomainModel.Concrete

{

public class SqlProductsRepository : IProductsRepository

{

private Table<Product> productsTable;

public SqlProductsRepository(string connectionString)

{

productsTable = (new DataContext(connectionString)).GetTable<Product>();

}

public IQueryable<Product> Products

{

get { return productsTable; }

}

}

}

修改 ProductsController构造函数,连接到实际的sql操作.

public ProductsController()

{

// This is just temporary until we have more infrastructure in place

//productsRepository = new FakeProductsRepository();

// 临时使用

string connString = @"data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|SportStore.mdf;User Instance=true";

productsRepository = new SqlProductsRepository(connString);

}

F5编译运行。

clip_image007

使用Inversion of Control

下载Castle-Windsor-2.0 Castle-Windsor项目网站 http://www.castleproject.org。

http://downloads.sourceforge.net/project/castleproject/InversionOfControl/2.0/Castle-Windsor-2.0.zip?use_mirror=cdnetworks-kr-1

为Web项目引用 Castle.Core、Castle.MicroKernel、Castle.Windsor。

创建一个自定义的Controller Factory

在WebUI根目录创建类

public class WindsorControllerFactory : DefaultControllerFactory

{

WindsorContainer container;

// The constructor:

// 1. Sets up a new IoC container

// 2. Registers all components specified in web.config

// 3. Registers all controller types as components

public WindsorControllerFactory()

{

// Instantiate a container, taking configuration from web.config

container = new WindsorContainer(

new XmlInterpreter(new ConfigResource("castle"))

);

// Also register all the controller types as transient

var controllerTypes = from t in Assembly.GetExecutingAssembly().GetTypes()

where typeof(IController).IsAssignableFrom(t)

select t;

foreach (Type t in controllerTypes)

container.AddComponentLifeStyle(t.FullName, t, LifestyleType.Transient);

}

// Constructs the controller instance needed to service each request

protected override IController GetControllerInstance(System.Web.Routing.RequestContext requestContext, Type controllerType)

{

return (IController)container.Resolve(controllerType);

}}

打开web.config文件添加

<add name="ApplicationServices" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true" providerName="System.Data.SqlClient"/>

</connectionStrings>

插入castle配置节

clip_image008

打开Global.asax.cs 添加自定义的Controller。

protected void Application_Start()

{

AreaRegistration.RegisterAllAreas();

RegisterRoutes(RouteTable.Routes);

ControllerBuilder.Current.SetControllerFactory(new WindsorControllerFactory());

}

使用自己的注入

ProductsController是通过硬编码依赖于SqlProductsRepository。通过使用 Ioc来将实际使用的Controller通过配置文件来动态载入。

修改ProductsController的构造函数。

public ProductsController(IProductsRepository productsRepository)

{

this.productsRepository = productsRepository;

}

修改配置文件

<castle>

<components>

<component id="ProdsRepository"

service="DomainModel.Abstract.IProductsRepository, DomainModel"

type="DomainModel.Concrete.SqlProductsRepository, DomainModel">

<parameters>

<connectionString>data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|SportStore.mdf;User Instance=true</connectionString>

</parameters>

</component>

</components>

</castle>

设置IoC组件的lifestyle。

<component id="ProdsRepository"

service="DomainModel.Abstract.IProductsRepository, DomainModel"

type="DomainModel.Concrete.SqlProductsRepository, DomainModel"

lifestyle="PerWebRequest"

>

Castle Windsor可以选的 lifystyle有 Transient, Singleton, PerWebRequest, Pooled, and Custom

注册 Windsor的 PreRequestLifestyle到 <httpModules>

<httpModules>

<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>

<add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>

<add name="PerRequestLifestyle"

type="Castle.MicroKernel.Lifestyle.PerWebRequestLifestyleModule,
 />

Castle.MicroKernel"

</httpModules>

F5 RUN

转载请注明出处! Author: im@xingquan.org

posted @ 2011-03-24 18:42  敏捷学院  阅读(719)  评论(0编辑  收藏  举报