WebApi学习笔记06:使用webapi模板--仓储模式--Unity依赖注入

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-08-04 01:15:23

WebApi学习笔记06:使用webapi模板--仓储模式--Unity依赖注入的相关文章

6.在MVC中使用泛型仓储模式和依赖注入实现增删查改

原文链接:http://www.c-sharpcorner.com/UploadFile/3d39b4/crud-operations-using-the-generic-repository-pattern-and-dep/ 系列目录: Relationship in Entity Framework Using Code First Approach With Fluent API[[使用EF Code-First方式和Fluent API来探讨EF中的关系]] Code First Mig

WebApi学习笔记01:webapi框架--控制器--路由

1.解决方案 1.1概述 一个解决方案里可以包含多个项目:也可以新建“解决方案文件夹”来逻辑(不是物理存在的文件夹)划分包含项目. 1.2创建方案 打开VS,文件->新建->项目: 2.Web项目 2.1概述 本例主要介绍安装WebApi框架,因为它几乎可以寄宿在任何项目中,先从空web模板项目,也不包含核心引用开始…… 2.1创建项目 在“解决方案资源管理器”中右键,添加->新建项目: 选择模板: 2.3安装webapi 在vs中,工具->NuGet程序包管理器->管理解决

WebAPi学习笔记之一 初识WebApi

公司这几天接了个APP项目,项目中要使用WebApi来作为服务端和客户端的数据交换层.于是我就被老板要求学习WebApi了. 对于ASP.Net相关知识为零的我来说,这无疑是一个难题.学习了这么久终于摸到了点门路.WebApi的定位很容易,它就是用来控制服务端和数据段数据转换的. WebApi包括控制器,路由,类model等几大内容: 类model:主要用来保存数据的. 控制器:主要用来根据客户端的method类型的响应, 路由:根据客户端的request URL来选择使用哪一个控制器,或者生成

Java框架spring Boot学习笔记(七):基于构造函数的依赖注入

编写User.java 1 package com.example.spring; 2 3 public class User { 4 private String name; 5 private Integer age; 6 private String country; 7 8 public User(String name, Integer age, String country) { 9 this.name = name; 10 this.age = age; 11 this.count

Asp.Net Core WebApi学习笔记(四)-- Middleware

Asp.Net Core WebApi学习笔记(四)-- Middleware 本文记录了Asp.Net管道模型和Asp.Net Core的Middleware模型的对比,并在上一篇的基础上增加Middleware功能支持. 在演示Middleware功能之前,先要了解一下Asp.Net管道模型发生了什么样的变化. 第一部分:管道模型 1. Asp.Net管道 在之前的Asp.Net里,主要的管道模型流程如下图所示: 请求进入Asp.Net工作进程后,由进程创建HttpWorkRequest对象

Django学习笔记(二)—— 模板

疯狂的暑假学习之 Django学习笔记(二)-- 模板 参考: <The Django Book> 第四章 一.模板基础知识 1.模板是如何工作的 用 python manage.py shell 启动交互界面(因为manage.py 保存了Django的配置,如果直接python启动交互界面运行下面代码会出错) 输入下面代码 >>> from django import template >>> t = template.Template('My name

iOS学习笔记06—Category和Extension

iOS学习笔记06—Category和Extension 一.概述 类别是一种为现有的类添加新方法的方式. 利用Objective-C的动态运行时分配机制,Category提供了一种比继承(inheritance)更为简洁的方法来对class进行扩展,无需创建对象类的子类就能为现有的类添加新方法,可以为任何已经存在的class添加方法,包括那些没有源代码的类(如某些框架类). 二.示例 1.声明类别 @interface NSString (CategoryDemo) -(NSNumber*)

《30天自制操作系统》笔记(06)——CPU的32位模式

<30天自制操作系统>笔记(06)--CPU的32位模式 进度回顾 上一篇中实现了启用鼠标.键盘的功能.屏幕上会显示出用户按键.点击鼠标的情况.这是通过设置硬件的中断函数实现的,可以说硬件本身的设计就具有事件驱动的性质,所以软件层面上才有基于事件的消息机制. 但上一篇没有说明中断的来龙去脉,本篇就从头到尾描述一下CPU与此相关的设置问题. Segment 32位的CPU使用32条地址线,能区分232=4G个内存地址.每个内存地址都有1Byte的内容. 分段,就是将4GB的内存分成很多块(blo

thinkphp学习笔记3—项目编译和调试模式

原文:thinkphp学习笔记3-项目编译和调试模式 1.项目编译 在章节2.4项目编译中作者讲到使用thinkphp的项目在第一次运行的时候会吧核心需要加载的文件去掉空白和注释合并到一个文件中编译并缓存,第二次运行时直接载入编译缓存,这样省去一些IO开销,加快执行速度.并且在3.0以上的版本中海做了一些优化: 1.合并和兴编译缓存和项目编译缓存,不再生成两个缓存文件 2.直接对本地环境生成设置和常量定义减少环境判断 3.编译缓存可以直接替换框架入口甚至项目入口,甚至脱离框架独立运行 4.通过参