在上一篇关于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. 解决JBoss只能通过localhost访问不能通过IP的问题

    前序 现在EJB是真的有点落伍了么,网上找点资料都挺难的样子,而且都是很久的了..好吧,最近对EJB有点兴趣学习一下,结果下载到服务器启动后,居然不能直接通过服务器IP访问,也是醉了,默认只能通过本地 ...

  2. centos7 修改中文字符集

    CentOS 7字符集的问题与6有点区别,会出现下面问题,查看是中文,vi进入就变成乱码了 生产中修改配置文件   [root@ce1d2002a999 ~]# cat /etc/locale.con ...

  3. python的学习之路day6

    大纲: 1.反射 其中的方法:getattr,delattr,setattr,hasattr __import__() __import__() 注意事项 2.模块中的特殊变量 __doc__ __c ...

  4. 小程序码B接口生成出错:场景内容包含非法字符

    由于包含了非法字符,微信返回的字节不超过100字符,但是没有包含提示内容,因此很难识别发现问题所在

  5. git 学习汇总

    生成gitignore 文件: https://gitignore.io/ git 版本回退 git reset --hard HEAD^ 上一个版本就是HEAD^,上上一个版本就是HEAD^^,当然 ...

  6. Django有关的所有命令

    1. Django的安装 pip install django ==1.11.11 pip install -i yuan django==1.11.11 2. 创建项目 django-admin s ...

  7. 团队作业——Alpha冲刺 9/12

    团队作业--Alpha冲刺 冲刺任务安排 杨光海天 今日任务:修复编辑界面与弹窗界面合并中出现的BUG 明日任务:希望完成编辑界面所有接口交互的功能 郭剑南 今日任务:优化图像预处理所有功能的函数代码 ...

  8. sourceTree跳过注册

    sourceTree是一个很方便的git管理工具,但是现在一直无法注册,本文记录了跳过注册的方法. 将下面的代码赋值到地址栏 %LocalAppData%\Atlassian\SourceTree\ ...

  9. 关于flex的crossdomain.xml文件存放目录

    最近在项目中遇到flex跨域访问的安全沙箱问题,查资料了解到需要在服务端加上crossdomain.xml文件,即: <?xml version="1.0" encoding ...

  10. 腾讯课堂老师qq号码转换成 teacherid

    result = 215696775^858006833 if(result){ result=4294967296+result; } alert(result);