快速上手EF+WebApi开发

本文只做WebApi开发入门参考,作为个人学习之用,无太多技术难度!

首先:建立一个空白solution,新建一个数据访问层DAL类库项目WebApiStart.DAL,右键引用,管理NuGet程序包,搜索“entityframwork”并安装;

如下图所示:

步骤2:新建WebApiStart.Model层:新建User类

    public class User
    {
        public int ID { get; set; }
        public string UserName { get; set; }
    }

 步骤3:在DAL层中引用Model层,新建UserContext类继承DbContext,

public class UserContext: DbContext
    {
        public UserContext() : base("sqlConn") { }

        public DbSet<User> SysUsers { get; set; }
    }

上面“sqlConn”为后面将要配置数据库连接字符串的name 值.

接着引入仓储模式:新建如下类:

public interface IBaseRepository<TEntiry> where TEntiry : class
    {
        IEnumerable<TEntiry> Get();
        TEntiry GetEntityByID(object id);
        void Insert(TEntiry entity);
        void Delete(object id);
        void Update(TEntiry entity);
    }
 public class BaseRepository<T> : IBaseRepository<T> where T :class
    {
        DbSet<T> dbSet;
        UserContext context = null;

        public BaseRepository(UserContext context)
        {
            dbSet = context.Set<T>();
            this.context = context;
        }

        public void Delete(object id)
        {
            T target = GetEntityByID(id);
            dbSet.Remove(target);
            context.SaveChangesAsync();
        }

        public IEnumerable<T> Get()
        {
            return dbSet.ToArray();
        }

        public T GetEntityByID(object id)
        {
            return dbSet.Find(id);
        }

        public void Insert(T entity)
        {
            dbSet.Add(entity);
            context.SaveChangesAsync();
        }

        public void Update(T entity)
        {
            dbSet.Attach(entity);
            context.Entry(entity).State = EntityState.Modified;
            context.SaveChangesAsync();
        }
    }

 至此,我们已经准备好了所有数据库相关的操作。

步骤4:新建一个控制台宿主WebApi程序:如下图所示:

 在控制台项目中写入如下代码:

static void Main(string[] args)
        {
            var config = new HttpSelfHostConfiguration("http://localhost:8080");

            config.Routes.MapHttpRoute(
                "API Default", "api/{controller}/{action}/{id}",
                new { id = RouteParameter.Optional });

            using (HttpSelfHostServer server = new HttpSelfHostServer(config))
            {
                server.OpenAsync().Wait();
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("服务已启动..");
                Console.ReadLine();
            }
        }

新建一个控制器: 

public class UserController:ApiController
    {
        IBaseRepository<User> userRepo;

        public UserController()
        {
            this.userRepo = new BaseRepository<User>(new UserContext());
        }

        public UserController(IBaseRepository<User> ur)
        {
            this.userRepo = ur;
        }

        public IEnumerable<User> GetUser()
        {
            return userRepo.Get();
        }

        [HttpPost]
        public void Delete(int id)
        {
            userRepo.Delete(id);
        }

把DAL层的app.config项复制到控制台程序的App.config中,新增数据库连接字符串配置:

运行控制台程序,启动Postman ,新建一个请求:

运行正常。

步骤5:在控制台宿主程序中引入IoC Unity:

新建UnityContainer

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();
        }


    }

改进Main方法:

static void Main(string[] args)
        {
            var config = new HttpSelfHostConfiguration("http://localhost:8080");
            // Web API 配置和服务
            var container = new UnityContainer();
            container.RegisterType(typeof(IBaseRepository<>), typeof(BaseRepository<>), new HierarchicalLifetimeManager());
            config.DependencyResolver = new UnityResolver(container);
            //container.RegisterType<String>(new InjectionFactory(c => "Hello,World"));
            config.Routes.MapHttpRoute(
                "API Default", "api/{controller}/{action}/{id}",
                new { id = RouteParameter.Optional });

            using (HttpSelfHostServer server = new HttpSelfHostServer(config))
            {
                server.OpenAsync().Wait();
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("服务已启动..");
                Console.ReadLine();
            }
        }

引入Unity后BaseRepository构造函数的加载是自动由容器实例化的,如果此时需要额外的参数,例如多了一个字符串参数,Unity是如何对字符串赋值的呢?如果不做任何处理,此时调用的是无参构造函数。如需要让Unity自动构建接口服务的机制生效,需要对参数进行注册:

如下代码:container.RegisterType<String>(new InjectionFactory(c => "Hello,World")); 

public UserController()
        {
            this.userRepo = new BaseRepository<User>(new UserContext());
        }

        public UserController(IBaseRepository<User> ur,string outParameter)
        {
            this.userRepo = ur;
        }

 

至此一个简单demo完成,  可以学习了解的内容为:IoC在Asp.NET WebAPI/MVC中的应用;

最后引入UnitOfWork模式:

  public class UnitOfWork : IDisposable
    {
        UserContext context = new UserContext();
        BaseRepository<User> userRepo;

        public BaseRepository<User> UserRepo
        {
            get
            {
                if (userRepo == null)
                {
                    this.userRepo = new BaseRepository<User>(context);
                }
                return userRepo;
            }
        }
        
        private bool disposed = false;
        protected virtual void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing) { context.Dispose(); }
            }
            this.disposed = true;
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        public void Save()
        {
            context.SaveChanges();
        }

改进UserController如下;

 public class UserController:ApiController
    {
        //IBaseRepository<User> userRepo;
        UnitOfWork uw = new UnitOfWork();
        public IEnumerable<User> GetUser()
        {
            return uw.UserRepo.Get();
        }
    }

运行效果同上面一致。 

一个上手的小Demo就完成了,一般建立WebApi流程大致包含如下内容:

参考链接:http://www.cnblogs.com/ruanyifeng/p/5455105.html

https://www.cnblogs.com/MuNet/articles/5649610.html

创建WebAPI项目流程

  1. 创建DAL
  2. 创建Repository和Unit of Work
  3. 创建Entities
  4. 创建Services
  5. 创建WebAPI
  6. 创建IOC
  7. 使用MEF解耦依赖注册关系
  8. 自定义路由
  9. 创建Exception处理和日志功能
  10. 创建单元测试
展开阅读全文

没有更多推荐了,返回首页