前言

其实就是一个简单依赖注入的三层架构。记录一下,大佬们就不用看下去了。重点在最后面,可以直接拖到底去看。

正文

1、贴代码

1、整体的一个结构。大佬们应该一眼就看明白了。

2、MySqlContext

using  Model;
using Microsoft.EntityFrameworkCore; namespace DbFactory
{
public class MySqlContext : DbContext
{
public MySqlContext(DbContextOptions<MySqlContext> options)
: base(options)
{
} public DbSet<Class> Class { get; set; } }
}

3、IBaseRepository.cs

using System;
using System.Linq;
using System.Linq.Expressions; namespace IRepository
{
public interface IBaseRepository<T, TKey> : IDisposable where T : class
{
T Find(TKey id);
T Find(Expression<Func<T, bool>> wherelamb);
void Add(T entity, bool isSaveChage = true);
bool Update(T entity, bool isSaveChage = true);
bool Delete(T entity, bool isSaveChage = true);
int Delete(params int[] ids);
IQueryable<T> LoadEntities(Expression<Func<T, bool>> whereLambda);
IQueryable<T> LoadPageEntities<S>(int pageSize, int pageIndex, out int total, Expression<Func<T, bool>> whereLambda, Expression<Func<T, S>> orderbyLambda, bool isAsc);
int SaveChange(); }
}

4、IClassRepository.cs

using  Model;

namespace  IRepository
{
public interface IClassRepository : IBaseRepository<Class, int>
{
}
}

5、IBaseService.cs

using  IRepository;

namespace  IService
{
public interface IBaseService<T, TKey> : IBaseRepository<T, TKey> where T : class
{ }
}

6、IClassService.cs

using  Model;
using System; namespace IService
{
public interface IClassService : IBaseService<Class, int>
{
}
}

7、BaseRepository.cs

using  DbFactory;
using IRepository;
using Microsoft.EntityFrameworkCore;
using System;
using System.Linq;
using System.Linq.Expressions; namespace Repository
{
public class BaseRepository<T, TKey> : IBaseRepository<T, TKey> where T : class
{
private MySqlContext _context; protected bool disposedValue; public BaseRepository(MySqlContext context)
{
_context = context; }
public T Find(TKey id)
{
return _context.Set<T>().Find(id);
} public T Find(Expression<Func<T, bool>> wherelamb)
{
return _context.Set<T>().AsNoTracking().FirstOrDefault();
} public virtual bool Update(T entity, bool isSaveChage = true)
{
_context.Entry(entity).State = EntityState.Modified;
if (isSaveChage)
{
SaveChange();
}
return true;
} public virtual bool Delete(T entity, bool isSaveChage = true)
{
_context.Entry(entity).State = EntityState.Deleted;
if (isSaveChage)
{
SaveChange();
}
return true; } public virtual int Delete(params int[] ids)
{
foreach (var item in ids)
{
var entity = _context.Set<T>().Find(item);
_context.Set<T>().Remove(entity);
}
SaveChange();
return ids.Count();
} public IQueryable<T> LoadEntities(Expression<Func<T, bool>> whereLambda)
{
return _context.Set<T>().Where(whereLambda).AsQueryable();
} public IQueryable<T> LoadPageEntities<S>(int pageSize, int pageIndex, out int total, Expression<Func<T, bool>> whereLambda, Expression<Func<T, S>> orderbyLambda, bool isAsc)
{
total = _context.Set<T>().Where(whereLambda).Count();
if (isAsc)
{
return
_context.Set<T>()
.Where(whereLambda)
.OrderBy(orderbyLambda)
.Skip(pageSize * (pageIndex - 1))
.Take(pageSize)
.AsQueryable();
}
else
{
return
_context.Set<T>()
.Where(whereLambda)
.OrderByDescending(orderbyLambda)
.Skip(pageSize * (pageIndex - 1))
.Take(pageSize)
.AsQueryable();
}
} protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
_context?.Dispose();
}
disposedValue = true;
}
} public void Dispose()
{
Dispose(true);
} public void Add(T entity, bool isSaveChage = true)
{
_context.Set<T>().Add(entity);
if (isSaveChage)
{
SaveChange();
}
} public int SaveChange()
{
return _context.SaveChanges();
}
}
}

8、ClassRepository

using  DbFactory;
using IRepository;
using Model; namespace Repository
{
public class ClassRepository : BaseRepository<Class, int>, IClassRepository
{
private MySqlContext _context;
public ClassRepository(MySqlContext Dbcontext) : base(Dbcontext)
{
_context = Dbcontext;
} }
}

9、BaseService

using  IRepository;
using IService;
using System;
using System.Linq;
using System.Linq.Expressions; namespace Service
{
public class BaseService<T, TKey> : IBaseService<T, TKey> where T : class
{
private readonly IBaseRepository<T, TKey> _repository;
public BaseService(IBaseRepository<T, TKey> repository)
{
_repository = repository;
} public T Find(TKey id)
{
return _repository.Find(id);
} public T Find(Expression<Func<T, bool>> wherelamb)
{
return _repository.Find(wherelamb);
} public IQueryable<T> LoadEntities(Expression<Func<T, bool>> whereLambda)
{
return _repository.LoadEntities(whereLambda);
} public IQueryable<T> LoadPageEntities<S>(int pageSize, int pageIndex, out int total, Expression<Func<T, bool>> whereLambda, Expression<Func<T, S>> orderbyLambda, bool isAsc)
{
return _repository.LoadPageEntities(pageSize, pageIndex, out total, whereLambda, orderbyLambda, isAsc);
} public int SaveChange()
{
return _repository.SaveChange();
} public bool Update(T entity, bool isSaveChage = true)
{
return _repository.Update(entity, isSaveChage);
} public void Add(T entity, bool isSaveChage = true)
{
_repository.Add(entity, isSaveChage = true);
}
public bool Delete(T entity, bool isSaveChage = true)
{
return _repository.Delete(entity, isSaveChage);
} public int Delete(params int[] ids)
{
return _repository.Delete(ids);
}
public void Dispose()
{
_repository.Dispose();
}
}
}

10、ClassService

using  IRepository;
using IService;
using Model; namespace Service
{
public class ClassService : BaseService<Class, int>, IClassService
{
private readonly IClassRepository _repository;
public ClassService(IClassRepository repository) : base(repository)
{
_repository = repository;
} }
}

11、DBExtensions

using  DbFactory;
using Repository;
using Autofac;
using Autofac.Extensions.DependencyInjection;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System; namespace Service
{
public static class DBExtensions
{
public static IHostBuilder UseMySql(this IHostBuilder hostBuilder, string connectionString = "")
{
try
{
if (string.IsNullOrEmpty(connectionString))
{
//TODO:连接字符串从Zookeeper
//connectionString = Core.Configs.Get<string>("Connection.MySql");
connectionString = "Server=192.168.1.179;User ID=root;Password=root;Database=db1;";
}
return hostBuilder.UseServiceProviderFactory(new AutofacServiceProviderFactory())
.ConfigureServices((ctx, services) =>
{
services.AddDbContext<MySqlContext>(options => options.UseMySql(connectionString, b => b.MigrationsAssembly("Test"))); })
.ConfigureContainer<ContainerBuilder>((context, builder) =>
{
builder.RegisterAssemblyTypes(typeof(BaseRepository<,>).Assembly)
.Where(t => t.Name.EndsWith("Repository"))
.AsImplementedInterfaces();
builder.RegisterAssemblyTypes(typeof(BaseService<,>).Assembly)
.Where(t => t.Name.EndsWith("Service"))
.AsImplementedInterfaces();
});
}
catch (System.Exception ex)
{ throw;
} }
public static IServiceProvider UseMySql(this IServiceCollection services, string connectionString = "")
{
if (string.IsNullOrEmpty(connectionString))
{
//TODO:连接字符串从Zookeeper
//connectionString = Core.Configs.Get<string>("Connection.MySql");
}
connectionString = "Server=192.168.1.179;User ID=root;Password=root;Database=db1;"; services.AddDbContext<MySqlContext>(options =>
options.UseMySql(connectionString, b => b.MigrationsAssembly("Test"))); var builder = new ContainerBuilder(); builder.Populate(services);
builder.RegisterAssemblyTypes(typeof(BaseRepository<,>).Assembly)
.Where(t => t.Name.EndsWith("Repository"))
.AsImplementedInterfaces();
builder.RegisterAssemblyTypes(typeof(BaseService<,>).Assembly)
.Where(t => t.Name.EndsWith("Service"))
.AsImplementedInterfaces(); return new AutofacServiceProvider(builder.Build());
}
}
}

2、调用

控制台

新建控制台程序TestConsoleApp

1、Program

using  Service;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System; namespace TestConsoleApp
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!"); CreateDefaultHost(args).Build().Run();
}
static IHostBuilder CreateDefaultHost(string[] args) => new HostBuilder()
.ConfigureServices((ctx, services) =>
{
services.AddHostedService<TestService>();
})
.UseMySql(); //就这样引用一下就好了
}
}

2、TestService

using  IService;
using Microsoft.Extensions.Hosting;
using System;
using System.Threading;
using System.Threading.Tasks; namespace TestConsoleApp
{ internal class TestService : IHostedService, IDisposable
{ IClassService _classService;
public TestService(IClassService classService)
{
_classService = classService;
} private Timer _timer; public Task StartAsync(CancellationToken cancellationToken)
{
Console.WriteLine("starting."); _timer = new Timer(DoWork, null, TimeSpan.Zero,
TimeSpan.FromSeconds(5)); return Task.CompletedTask;
} private void DoWork(object state)
{
Console.WriteLine("-------------------------------");
var s = _classService.Find(x => true).Id;
Console.WriteLine(s);
Console.WriteLine("working.");
} public void Dispose()
{
_timer?.Dispose();
} public Task StopAsync(CancellationToken cancellationToken) => throw new NotImplementedException();
}
}

3、RUN

每5秒就会查询一次。

WEB

这里就不演示了,这样services.UseMySql()就可以了。

using Service;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;

重点

那就是DBExtensions

关于Autofac的使用,网上大多都是这样的。

但是我要使用IHostBuilder的扩展。改成这样就好了。

.NETCore+EF+MySql+Autofac简单三层架构的更多相关文章

  1. 基于EF+WCF的通用三层架构及解析

    分享基于EF+WCF的通用三层架构及解析 本项目结合EF 4.3及WCF实现了经典三层架构,各层面向接口,WCF实现SOA,Repository封装调用,在此基础上实现了WCFContext,动态服务 ...

  2. Net系列框架-Dapper+简单三层架构

    Net系列框架-Dapper+简单三层架构 工作将近6年多了,工作中也陆陆续续学习和搭建了不少的框架,后续将按由浅入深的方式,整理出一些框架源码,所有框架源码本人都亲自调试通过,如果有问题,欢迎联系我 ...

  3. Spring Boot demo系列(二):简单三层架构Web应用

    2021.2.24 更新 1 概述 这是Spring Boot的第二个Demo,一个只有三层架构的极简Web应用,持久层使用的是MyBatis. 2 架构 一个最简单的Spring Boot Web应 ...

  4. 分享基于EF+WCF的通用三层架构及解析

    本项目结合EF 4.3及WCF实现了经典三层架构,各层面向接口,WCF实现SOA,Repository封装调用,在此基础上实现了WCFContext,动态服务调用及一个分页的实例. 1. 项目架构图: ...

  5. Asp.Net MVC简单三层架构(MVC5+EF6)

    三层架构与MVC的关系 三层架构是一个分层式的软件体系架构设计,分为:表现层(UI).业务逻辑层(BLL).数据访问层(DAL).分层的目的是为了实现“高内聚,低耦合”的思想,有利于系统后期的维护.更 ...

  6. NetCore +EF+Mysql 从数据库生成实体类到项目

    1.点击“工具”->“NuGet包管理器”->“程序包管理器控制台” 分别安装以下几个包 Mysql 版本: Install-Package MySql.Data.EntityFramew ...

  7. Unity V3 初步使用 —— 为我的.NET项目从简单三层架构转到IOC做准备

    [声明]由于本人表达能力有限,为避免不必要的误人子弟,本文将不会涉及IOC与DI,仅仅描述新版本Unity 3的使用(非Unity 3D,如果您想看的是Unity 3D请立即离开,否则莫怪此处“谋财害 ...

  8. MVC项目实践,在三层架构下实现SportsStore-01,EF Code First建模、DAL层等

    SportsStore是<精通ASP.NET MVC3框架(第三版)>中演示的MVC项目,在该项目中涵盖了MVC的众多方面,包括:使用DI容器.URL优化.导航.分页.购物车.订单.产品管 ...

  9. C#简单三层结构设计UI、BLL、DAL、Model实际项目应用例子

    C#简单三层结构设计UI.BLL.DAL .Model实际项目应用例子 在实际项目中,程序设计都有他的层次结构,比如MVC.MVP.普通的三层结构等等,不过现在用三层结构的相比可能少了,但是也有一些小 ...

随机推荐

  1. ArcGis SOE(server object extensions)之REST Template初体验

    一.安装vs和arcgis server for .net(本例是vs2010.as 10),然后打开vs新建一个项目

  2. Django+xadmin打造在线教育平台(九)

    目录 在线教育平台(一)      在线教育平台(二) 在线教育平台(三)      在线教育平台(四) 在线教育平台(五)      在线教育平台(六) 在线教育平台(七)      在线教育平台( ...

  3. ScalaPB(4): 通用跨系统protobuf数据,sbt设置

    我们知道,在集群环境节点之间进行交换的数据必须经过序列化/反序列化处理过程,而在这方面protobuf是一个比较高效.易用的模式.用户首先在.proto文件中用IDL来定义系统中各种需要进行交换的数据 ...

  4. DDD实战进阶第一波(十):开发一般业务的大健康行业直销系统(实现经销商登录仓储与逻辑)

    上一篇文章主要讲了经销商注册的仓储和领域逻辑的实现,我们先把应用服务协调完成经销商注册这部分暂停一下,后面文章统一讲. 这篇文章主要讲讲经销商登录的仓储和相关逻辑的实现. 在现代应用程序前后端分离的实 ...

  5. PAT1121:Damn Single

    1121. Damn Single (25) 时间限制 300 ms 内存限制 65536 kB 代码长度限制 16000 B 判题程序 Standard 作者 CHEN, Yue "Dam ...

  6. C++相关:C++的IO库

    前言 基本的IO库设施 istream(输入流类型),提供输入操作. ostream(输出流类型),提供输出操作. cin,一个istream对象,从标准输入读取数据. cout,一个ostream对 ...

  7. 图解MySQL索引--B-Tree(B+Tree)

    看了很多关于索引的博客,讲的大同小异.但是始终没有让我明白关于索引的一些概念,如B-Tree索引,Hash索引,唯一索引....或许有很多人和我一样,没搞清楚概念就开始研究B-Tree,B+Tree等 ...

  8. springBoot+springSecurity 数据库动态管理用户、角色、权限

    使用spring Security3的四种方法概述 那么在Spring Security3的使用中,有4种方法: 一种是全部利用配置文件,将用户.权限.资源(url)硬编码在xml文件中,已经实现过, ...

  9. JavaWeb学习(一) ---- HTTP以及Tomcat的安装及使用

    HTTP 一.协议 双方在交互.通讯的时候,遵循的一种规范,一种规则. 二.HTTP协议 HTTP的全名是:Hypertext Transfer Protocol(超文本传输协议),针对网络上的客户端 ...

  10. python中读写excel并存入mysql

    为了一个突如其来的想法:用python简单解决就好.现在算是把这个项目需要的基础功能坑都填完了.剩下就是AI和数据展示方面的坑了. 今天遇到的坑是: 1.从excel读出的中文是乱码 2.中文写入my ...