1.Web项目
1.1概述
对数据操作封装使用存储模式是很常见的方式,而使用依赖注入来降低耦合度(方便创建对象,可以抛弃经典的工厂模式)……
1.2创建项目
1.3添加模型
在Models下,添加Product.cs:
namespace WebApi06.Models { public class Product { public int ID { get; set; } public string Name { get; set; } public decimal Price { get; set; } } }
1.4安装EF
1.5添加上下文类
在Models下,添加EFContext.cs
using System.Data.Entity; namespace WebApi06.Models { public class EFContext : DbContext { public EFContext() : base("name=ProductsContext") { } public DbSet<Product> Products { get; set; } } }
1.6数据库连接字符串
在Web.config里<configuration>节点下,添加下面代码:
<connectionStrings> <add name="ProductsContext" connectionString="Data Source=(localdb)\v11.0; Initial Catalog=ProductDB; Integrated Security=True; MultipleActiveResultSets=True; AttachDbFilename=|DataDirectory|ProductDB.mdf" providerName="System.Data.SqlClient" /> </connectionStrings>
1.7仓储接口
在Models下,添加IProductRepository.cs,其代码:
using System.Collections.Generic; namespace WebApi06.Models { public interface IProductRepository { IEnumerable<Product> GetAll(); Product GetByID(int id); void Add(Product product); } }
1.8存储实现
在Models下,添加ProductRepository.cs,其代码:
using System; using System.Collections.Generic; using System.Linq; namespace WebApi06.Models { public class ProductRepository : IDisposable, IProductRepository { private EFContext db = new EFContext(); public IEnumerable<Product> GetAll() { return db.Products; } public Product GetByID(int id) { return db.Products.FirstOrDefault(p => p.ID == id); } public void Add(Product product) { db.Products.Add(product); db.SaveChanges(); } protected void Dispose(bool disposing) { if (disposing) { if (db != null) { db.Dispose(); db = null; } } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } } }
1.9添加控制器
在Controllers下,添加ProductsController.cs,其代码:
using System.Collections.Generic; using System.Web.Http; using WebApi06.Models; namespace WebApi06.Controllers { public class ProductsController : ApiController { // 直接new实现对象? //ProductRepository _repository = new ProductRepository(); private IProductRepository _repository; public ProductsController(IProductRepository repository) { _repository = repository; } public IEnumerable<Product> Get() { return _repository.GetAll(); } public IHttpActionResult Get(int id) { var product = _repository.GetByID(id); if (product == null) { return NotFound(); } return Ok(product); } } }
从代码注释可以看到,如果直接new具体对象,程序可以使用。但为了解耦,针对接口编程,这里用到构造函数。(并不知道实例化那个具体对象)
1.10安装Unity
1.11包装容器
在根目录,新建Resolver文件夹。在里面添加UnityResolver.cs
using Microsoft.Practices.Unity; using System; using System.Collections.Generic; using System.Web.Http.Dependencies; namespace WebApi06.Resolver { public class UnityResolver : IDependencyResolver { protected IUnityContainer container; public UnityResolver(IUnityContainer container) { if (container == null) { throw new ArgumentNullException("container"); } this.container = container; } public object GetService(Type serviceType) { try { return container.Resolve(serviceType); } catch (ResolutionFailedException) { return null; } } public IEnumerable<object> GetServices(Type serviceType) { try { return container.ResolveAll(serviceType); } catch (ResolutionFailedException) { return new List<object>(); } } public IDependencyScope BeginScope() { var child = container.CreateChildContainer(); return new UnityResolver(child); } public void Dispose() { container.Dispose(); } } }
1.12配置
修改App_Start\WebApiConfig.cs
using Microsoft.Practices.Unity; using System.Web.Http; using WebApi06.Models; using WebApi06.Resolver; namespace WebApi06 { public static class WebApiConfig { public static void Register(HttpConfiguration config) { // Web API 配置和服务 var container = new UnityContainer(); container.RegisterType<IProductRepository, ProductRepository>(new HierarchicalLifetimeManager()); config.DependencyResolver = new UnityResolver(container); // Web API 路由 config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); } } }
1.13初始化数据
使用上一章自动迁移方式即可,这里就不再重复了。
运行结果:
2.小结
本例学习的意义不大,一是仓储封装太简单,不全,应用采用泛型,也没有引入Unit Of Work(工作单元)。可能依赖注入了解一下还有点用。
时间: 2024-10-06 21:04:11