.netCoreMVC添加数据仓储
在上一篇关于CodeFirst从零搭建ASP.NETCore2.0中搭建起了完整.netCoreMVC项目,在这一篇中将实现如何注册service服务和Repository数据仓储到web中实现数据的统一处理.
首先新建项目:DotNetCore20.Service:
右键解决方案>新建项目:DotNetCore20.Service

添加repository
原先计划自己实现一套repository(将在后续计划再写一篇参考:https://github.com/Arch/UnitOfWork实现Repository的文章),但是由于时间原因后来在nuget中找到了更好更全面的解决方案,暂且利用第三方组件实现repository.
nuget搜索:Microsoft.EntityFrameworkCore.UnitOfWork;源代码:https://github.com/Arch/UnitOfWork

安装到DotNetCore20.Service

在DotNetCore20.Service中添加DemoService.cs和对应的接口IDemoService.cs,目录结构如下:

DemoService.cs:
using DotNetCore20.Entity;
using Microsoft.EntityFrameworkCore;
using System;
using System.Threading.Tasks; namespace DotNetCore20.Service
{
public class DemoService : IDemoService
{
private readonly IUnitOfWork _unitOfWork;
public DemoService(IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
} public async Task<UserExtend> Meth()
{
var repo = _unitOfWork.GetRepository<UserExtend>();
var value = await repo.FindAsync();
return value;
}
}
}
IDemoService:
using DotNetCore20.Entity;
using Microsoft.EntityFrameworkCore;
using System;
using System.Threading.Tasks; namespace DotNetCore20.Service
{
public interface IDemoService
{
Task<UserExtend> Meth();
}
}
Startup.cs中注册相关服务:
在Startup中的ConfigureServices方法中添加以下行:
//Customer's services
services.AddUnitOfWork<DotNetCoreDbContext>();//注册数据仓储
services.AddScoped(typeof(IDemoService), typeof(DemoService));//注册service,为了避免都要在此声明,所以之后会统一注册DotNetCore20.Service下的所有service
完整Startup如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using DotNetCore20.Web.Data;
using DotNetCore20.Web.Models;
using DotNetCore20.Web.Services;
using DotNetCore20.DAL.DbContext;
using DotNetCore20.Service; namespace DotNetCore20.Web
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
} public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); //自定义数据库连接字符串
services.AddDbContext<DotNetCoreDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DotNetCoreConnection"))); services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders(); // Add application services.
services.AddTransient<IEmailSender, AuthMessageSender>();
services.AddTransient<ISmsSender, AuthMessageSender>(); //Customer's services
services.AddUnitOfWork<DotNetCoreDbContext>();
services.AddScoped(typeof(IDemoService), typeof(DemoService)); services.AddMvc();
} // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
} app.UseStaticFiles(); app.UseAuthentication(); app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
Startup
HomeController:
在Controller的HomeController中的构造函数中添加以下代码:
public class HomeController : Controller
{
private IDemoService _demoService { get; set; }
public HomeController(IDemoService demoService)
{
_demoService = demoService;
}
}
使用Service
public IActionResult Index()
{
_demoService.Meth(); return View();
}
在此大功告成,点击
即可
.netCoreMVC添加数据仓储的更多相关文章
- 从零开始,搭建博客系统MVC5+EF6搭建框架(2),测试添加数据、集成Autofac依赖注入
一.测试仓储层.业务层是否能实现对数据库表的操作 1.创建IsysUserInfoRepository接口来继承IBaseRepository父接口 namespace Wchl.WMBlog.IRe ...
- 从零开始,搭建博客系统MVC5+EF6搭建框架(1),EF Code frist、实现泛型数据仓储以及业务逻辑
前言 从上篇30岁找份程序员的工作(伪程序员的独白),文章开始,我说过我要用我自学的技术,来搭建一个博客系统,也希望大家给点意见,另外我很感谢博客园的各位朋友们,对我那篇算是自我阶段总结文章 ...
- 【干货】利用MVC5+EF6搭建博客系统(二)测试添加数据、集成Autofac依赖注入
PS:如果图片模糊,鼠标右击复制图片网址,然后在浏览器中打开即可. 一.测试仓储层.业务层是否能实现对数据库表的操作 1.在52MVCBlog.IRepository程序集下创建IsysUserInf ...
- C#数据仓储类
https://ninesky.codeplex.com/SourceControl/latest /*============================== 版本:v0.1 创建:2016.2 ...
- C#向sql server数据表添加数据源代码
HoverTree解决方案 学习C#.NET,Sql Server,WinForm等的解决方案. 本文链接http://hovertree.com/h/bjaf/0jteg8cv.htm 使用的技术. ...
- js表单动态添加数据并提交
情景1:已经存在form对象了,动态为form增加对象并提交 function formAppendSubmit(){ var myform=$('#newArticleForm'); //得到for ...
- 使用C#类向数据库添加数据的例子源码
在上一篇中,增加了sql server数据库操作类SqlOperator,用于操作sql server数据库.还有一个SqlStringHelper类,用于处理sql语句的单引号.那么这两个类怎么使用 ...
- EF批量添加数据性能慢的问题的解决方案
//EF批量添加数据性能慢的问题的解决方案 public ActionResult BatchAdd() { using (var db = new ToneRoad.CEA.DbContext.Db ...
- mybatis+oracle添加一条数据并返回所添加数据的主键问题
最近做mybatis+oracle项目的时候解决添加一条数据并返回所添加数据的主键问题 controller层 @RequestMapping("/addplan") public ...
随机推荐
- 从外部导入django模块
import os import sys sys.path.append("D:\\pyweb\\sf"); # 项目位置(不是app) os.environ.setdefault ...
- Access restriction: The type BASE64Encoder is not accessible due to restriction on required library C:\Program Files\Java\jre6\lib\rt.jar
解决方案:在configure build path 中去掉 jre system library,然后重新加载jre system library.....
- Matlab feval函数(转)
http://zhidao.baidu.com/link?url=7CusQYQXhCDB8sUtolMEhI1ctnpblbYrpSnU0fhIh5LvDZuhsBuozQusS6Kb1McTp7x ...
- Spirng MVC 重定向传递对象
在 Spring MVC 中我们会经常遇到重定向. @RequestMapping("/order/saveorder.html") public String saveOrder ...
- sqlserver 镜像 断开连接 正在恢复+主机服务器关机用备用镜像
如果主机坏了断开连接就用备机的镜像数据库 --主备互换,备机sql命令 USE master; ALTER DATABASE test SET PARTNER FORCE_SERVICE_ALLO ...
- Java中Map根据键值(key)或者值(value)进行排序实现
我们都知道,java中的Map结构是key->value键值对存储的,而且根据Map的特性,同一个Map中 不存在两个Key相同的元素,而value不存在这个限制.换句话说,在同一个Map中Ke ...
- sublime设置node.js编译
1. 首先需安装node环境并配置好环境变量,安装教程. 2. 然后在sublime中打开工具(Tools)→编译系统(Build System)→新编译系统(New Build System) 3. ...
- 'No Transport' Error w/ jQuery ajax call in IE
I need to use foursquare API to search venues. Of course it is cross-domain. It has no any problems ...
- Promise 模式解析:Promise模式与异步及声明式编程
一.构建流程 1.(异步)数据源(请求)的构建:Promise的构建并执行请求: 2.处理流程的构建:then将处理函数保存: 二.处理: 1.请求的响应返回: 2.调用后继处理流程. 三. 1.构建 ...
- Vue那些事儿之用visual stuido code编写vue报的错误Elements in iteration expect to have 'v-bind:key' directives.
当用vsc打开我们的vue代码时,在其他编辑器里面本来没有错误,到这个编辑器里面 v-for就出毛病了.如下图所示, 那是因为我们打开了对vue进行Eslint的检查. 搜索vetur.validat ...