在上一篇关于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添加数据仓储的更多相关文章

  1. 从零开始,搭建博客系统MVC5+EF6搭建框架(2),测试添加数据、集成Autofac依赖注入

    一.测试仓储层.业务层是否能实现对数据库表的操作 1.创建IsysUserInfoRepository接口来继承IBaseRepository父接口 namespace Wchl.WMBlog.IRe ...

  2. 从零开始,搭建博客系统MVC5+EF6搭建框架(1),EF Code frist、实现泛型数据仓储以及业务逻辑

    前言      从上篇30岁找份程序员的工作(伪程序员的独白),文章开始,我说过我要用我自学的技术,来搭建一个博客系统,也希望大家给点意见,另外我很感谢博客园的各位朋友们,对我那篇算是自我阶段总结文章 ...

  3. 【干货】利用MVC5+EF6搭建博客系统(二)测试添加数据、集成Autofac依赖注入

    PS:如果图片模糊,鼠标右击复制图片网址,然后在浏览器中打开即可. 一.测试仓储层.业务层是否能实现对数据库表的操作 1.在52MVCBlog.IRepository程序集下创建IsysUserInf ...

  4. C#数据仓储类

    https://ninesky.codeplex.com/SourceControl/latest /*============================== 版本:v0.1 创建:2016.2 ...

  5. C#向sql server数据表添加数据源代码

    HoverTree解决方案 学习C#.NET,Sql Server,WinForm等的解决方案. 本文链接http://hovertree.com/h/bjaf/0jteg8cv.htm 使用的技术. ...

  6. js表单动态添加数据并提交

    情景1:已经存在form对象了,动态为form增加对象并提交 function formAppendSubmit(){ var myform=$('#newArticleForm'); //得到for ...

  7. 使用C#类向数据库添加数据的例子源码

    在上一篇中,增加了sql server数据库操作类SqlOperator,用于操作sql server数据库.还有一个SqlStringHelper类,用于处理sql语句的单引号.那么这两个类怎么使用 ...

  8. EF批量添加数据性能慢的问题的解决方案

    //EF批量添加数据性能慢的问题的解决方案 public ActionResult BatchAdd() { using (var db = new ToneRoad.CEA.DbContext.Db ...

  9. mybatis+oracle添加一条数据并返回所添加数据的主键问题

    最近做mybatis+oracle项目的时候解决添加一条数据并返回所添加数据的主键问题 controller层 @RequestMapping("/addplan") public ...

随机推荐

  1. 【MySQL 5.7 Reference Manual】15.4.2 Change Buffer(变更缓冲)

    15.4.2 Change Buffer(变更缓冲)   The change buffer is a special data structure that caches changes to se ...

  2. rsync 数据备份+cron+mailx案例

    大家都知道数据非常重要的,需要经常备份,如果备份了,但无法恢复还原,那就证明你备份的很失败,所有当我们备份了数据需要检查是否备份完整,是否可用可恢复.以下为一个企业案例: 某公司里有一台Web服务器, ...

  3. TMOUT优化终端超时

    有时候,管理员终端登陆了系统,如果离开没有退出账户,则会有安全隐患存在,因此需要优化终端超时. 设置终端超时: export TMOUT=10 永久生效: echo "export TMOU ...

  4. round()和trunc()用法

    round(数字 | 列 保留小数的位数):四舍五入. select a.*,round(s),round(-s) from bqh4 a trunc(数字 | 列 保留小数的位数):舍弃指定位置的内 ...

  5. PHP 定界符

    双引号和单引号是常用的字符串定界符,在php4.0以后 还可以使用字符串定界符<<<,功能和双引号差不多,用法如下 <<<标识符 字符串 标识符 其中最后的标识符必 ...

  6. 新人如何进入IT行业

    你遇到了我刚毕业时遇到的问题. 现在需要知道你希望在那里就业,上海和北京就业的待遇差不多,北京能比上海稍微少点(我是指你这类刚毕业的) 说主题好了 应届毕业,找工作都很难的,因为现在很多企业是不愿意找 ...

  7. 匿名访问windows server 2008 R2 文件服务器的共享

    匿名访问windows server 2008 R2 文件服务器的共享 匿名访问windows 2008 R2 文件服务器的共享,七步:第一步 取消简单文件共享:第二步 设置需要共享的文件夹every ...

  8. 7zip批量压缩,并批量改.jar

    批量压缩.bat--要和将要压缩的文件在同一级目录下 for /d %%X in (*) do "D:\Program Files\7-Zip\7z.exe" a "%% ...

  9. vbs常用函数

    aa '删除文件夹 sub DeleteFolder(objFolder) call OutputLog(objFolder.Path,true) err.Clear On Error Resume ...

  10. SDN2017 第四次实验作业

    实验目的 1.使用图形化界面搭建拓扑如下并连接控制器 2.使用python脚本搭建拓扑如下并通过命令行连接控制器 3.使用任一种方法搭建拓扑连接控制器后下发流表 实验步骤 建立以下拓扑,并连接上ODL ...