仓库初始化。包含DI项目

This commit is contained in:
falcon 2019-08-26 09:23:35 +08:00
commit 4f08b1f6e2
36 changed files with 1293 additions and 0 deletions

263
.gitignore vendored Normal file
View File

@ -0,0 +1,263 @@
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
zx_web/Files/errs/
# User-specific files
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
# Visual Studio 2015 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUNIT
*.VisualState.xml
TestResult.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# DNX
project.lock.json
project.fragment.lock.json
artifacts/
*_i.c
*_p.c
*_i.h
*.ilk
*.meta
*.obj
*.pch
*.pdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# JustCode is a .NET coding add-in
.JustCode
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# TODO: Comment the next line if you want to checkin your web deploy settings
# but database connection strings (with potential passwords) will be unencrypted
#*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# The packages folder can be ignored because of Package Restore
**/packages/*
# except build/, which is used as an MSBuild target.
!**/packages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/packages/repositories.config
# NuGet v3's project.json files produces more ignoreable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
node_modules/
orleans.codegen.cs
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
# SQL Server files
*.mdf
*.ldf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# JetBrains Rider
.idea/
*.sln.iml
# CodeRush
.cr/
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc

View File

@ -0,0 +1,21 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp2.2</TargetFramework>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="2.2.6" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.0.1" />
<PackageReference Include="MSTest.TestAdapter" Version="1.4.0" />
<PackageReference Include="MSTest.TestFramework" Version="1.4.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="2.2.6" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Falcon.AutoTableLog\Falcon.AutoTableLog.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,27 @@
using System.ComponentModel.DataAnnotations.Schema;
using Microsoft.EntityFrameworkCore;
namespace Falcon.AutoTableLog.Test
{
public static class MyDbContextFactory
{
public static MyDbContext Create() {
var option = new DbContextOptionsBuilder<MyDbContext>().UseInMemoryDatabase("MemDb").Options;
return new MyDbContext(option);
}
}
public class MyDbContext:DbContext
{
public MyDbContext(DbContextOptions options) : base(options) { }
public DbSet<Person> People { get; set; }
}
[Table("Person")]
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
}
}

View File

@ -0,0 +1,21 @@
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Falcon.AutoTableLog.Test
{
[TestClass]
public class DbContextAutoSaveLogTest
{
[TestMethod]
public void GetDbContextEventTest() {
using(var db=new MyDbContext()) {
var log = new DbContextAutoSaveLog<MyDbContext>(db);
log.GetDbContextEvent();
var newP = new Person { Name = "p1"};
db.Add(newP);
db.SaveChangesAsync().Wait();
}
}
}
}

View File

@ -0,0 +1,27 @@
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.EntityFrameworkCore;
using System.Linq;
using Microsoft.EntityFrameworkCore.ChangeTracking;
namespace Falcon.AutoTableLog
{
public class DbContextAutoSaveLog<TDbContext> where TDbContext : DbContext
{
public TDbContext Db { get; set; }
public DbContextAutoSaveLog(TDbContext db) {
this.Db = db;
}
public void GetDbContextEvent() {
this.Db.ChangeTracker.Tracked += (object sender,EntityTrackedEventArgs e) => {
var a = e.Entry.OriginalValues;
};
foreach(var en in this.Db.ChangeTracker.Entries()) {
}
}
}
}

View File

@ -0,0 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>netstandard2.0;NET461</TargetFrameworks>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="2.2.6" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,17 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>netcoreapp2.2;NET461;NET472</TargetFrameworks>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
<Description>缓冲组件,实现对数据的缓冲</Description>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(TargetFramework)|$(Platform)'=='Debug|netcoreapp2.2|AnyCPU'">
<DocumentationFile>C:\Documentation\develop\FalconCore\Falcon.Cache\Falcon.Cache.xml</DocumentationFile>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="StackExchange.Redis" Version="2.0.601" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,24 @@
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Falcon.DI;
using Microsoft.Extensions.DependencyInjection;
namespace Falcon.DI.Packget.Test
{
[TestClass]
public class FalconDITest
{
[TestMethod]
public void RunTest() {
IServiceCollection ser = new ServiceCollection();
ser.UseFalconDI();
var pd = ser.BuildServiceProvider();
IA obj = pd.GetService<IA>();
Assert.IsNotNull(obj);
}
}
public interface IA { }
[FalconDIRegister]
public class A:IA { }
}

View File

@ -0,0 +1,17 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp2.2</TargetFramework>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Falcon.DI" Version="1.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="2.2.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.0.1" />
<PackageReference Include="MSTest.TestAdapter" Version="1.4.0" />
<PackageReference Include="MSTest.TestFramework" Version="1.4.0" />
</ItemGroup>
</Project>

120
Falcon.DI.Test/DITest.cs Normal file
View File

@ -0,0 +1,120 @@
using System.Linq;
using System.Reflection;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Falcon.DI.Test
{
[TestClass]
public class UseFalconDITest
{
/// <summary>
/// 一般获取服务测试
/// </summary>
[TestMethod]
public void DITest() {
IServiceCollection ser = new ServiceCollection();
ser.UseFalconDI();
using(var pd = ser.BuildServiceProvider()) {
Assert.IsNotNull(pd.GetServices<IMyInterface>());
System.Console.WriteLine(pd.GetServices<IMyInterface>().Count());
Assert.IsTrue(pd.GetServices<IMyInterface>().Count() > 1);
Assert.IsNotNull(pd.GetService<IMyInterface>());
}
}
/// <summary>
/// 测试释放资源
/// </summary>
[TestMethod]
public void disableTest() {
IServiceCollection ser = new ServiceCollection();
ser.UseFalconDI();
var pd = ser.BuildServiceProvider();
var obj = pd.GetService<MyClassWithDisable>();
Assert.IsNotNull(obj);
Assert.AreEqual(1,MyClassWithDisable.Count);
pd.Dispose();
Assert.AreEqual(0,MyClassWithDisable.Count);
using(pd = ser.BuildServiceProvider()) {
obj = pd.GetService<MyClassWithDisable>();
Assert.IsNotNull(obj);
Assert.AreEqual(1,MyClassWithDisable.Count);
}
Assert.AreEqual(0,MyClassWithDisable.Count);
}
[TestMethod]
[Description("测试不提供完整构造注入参数")]
public void NotFullTest() {
IServiceCollection ser = new ServiceCollection();
ser.UseFalconDI();
var pd = ser.BuildServiceProvider();
var obj = pd.GetService<NotFullObj>();
Assert.IsNotNull(obj);
Assert.IsNotNull(obj.F1);
Assert.IsNull(obj.F2);
}
/// <summary>
/// 测试服务工厂
/// </summary>
[TestMethod]
public void IFalconDIFactoryTest() {
IServiceCollection ser = new ServiceCollection();
ser.UseFalconDI();
using(var pd = ser.BuildServiceProvider()) {
var obj = pd.GetService<IFalconDIInstantTypeFactory>();
Assert.IsNotNull(obj);
Assert.AreEqual(obj.Instance().Val,2);
var obj2 = pd.GetService<IFalconDIInstantFactory<IFDIIT>>();
Assert.IsNotNull(obj2);
Assert.AreEqual(obj2.Instance().Val,2);
}
}
/// <summary>
/// 测试注册到自身
/// </summary>
[TestMethod]
public void RegisterToSelf() {
IServiceCollection ser = new ServiceCollection();
ser.UseFalconDI();
using(var pd = ser.BuildServiceProvider()) {
var obj = pd.GetService<RegisterToSelf>();
Assert.IsNotNull(obj);
}
}
/// <summary>
/// 测试单例
/// </summary>
[TestMethod]
public void SingletonTest() {
IServiceCollection ser = new ServiceCollection();
ser.UseFalconDI();
//单例。两次获取为同一对象
using(var pd = ser.BuildServiceProvider()) {
var obj = pd.GetService<SingletonTest>();
Assert.IsTrue(obj.Val == 0);
obj.Val = 1;
var obj2 = pd.GetService<SingletonTest>();
Assert.IsTrue(obj.Val == 1);
}
//释放Provider后释放单例对象
using(var pd = ser.BuildServiceProvider()) {
var obj = pd.GetService<SingletonTest>();
Assert.IsTrue(obj.Val == 0);
obj.Val = 1;
var obj2 = pd.GetService<SingletonTest>();
Assert.IsTrue(obj.Val == 1);
}
}
}
}

View File

@ -0,0 +1,20 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp2.2</TargetFramework>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="2.2.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.0.1" />
<PackageReference Include="MSTest.TestAdapter" Version="1.4.0" />
<PackageReference Include="MSTest.TestFramework" Version="1.4.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Falcon.DI\Falcon.DI.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,33 @@
using System;
namespace Falcon.DI.Test
{
public interface IFDIIT
{
int Val { get; set; }
}
[FalconDIRegister]
public class FalconDIInstantType:IFDIIT
{
public int Val { get; set; } = 1;
}
public interface IFalconDIInstantTypeFactory:IFalconDIInstantFactory<IFDIIT> { }
[FalconDIRegister]
public class FalconDIInstantTypeFactory:IFalconDIInstantTypeFactory, IFalconDIInstantFactory<IFDIIT>
{
public IServiceProvider Provider { get; set; }
public FalconDIInstantTypeFactory(IServiceProvider sp = null) {
this.Provider = sp;
}
public IFDIIT Instance() {
return this.Provider == null ? new FalconDIInstantType { Val = 3 } :
new FalconDIInstantType { Val = 2 };
}
}
}

View File

@ -0,0 +1,44 @@
namespace Falcon.DI.Test
{
public interface IMyInterface
{
string Getname();
}
public interface IMyInterface2
{
string Getname();
}
[FalconDIRegister(typeof(IMyInterface))]
public class MyClassInterface:IMyInterface
{
public string Getname() {
return this.GetType().Name;
}
}
[FalconDIRegister]
public class MyClassInterfaces:IMyInterface, IMyInterface2
{
public string Getname() {
return this.GetType().Name;
}
}
[FalconDIRegister]
public class MyClassDefault:IMyInterface
{
public string Getname() {
return this.GetType().Name;
}
}
[FalconDIRegister(typeof(MyClassSelf))]
public class MyClassSelf:IMyInterface
{
public string Getname() {
return this.GetType().Name;
}
}
}

View File

@ -0,0 +1,20 @@

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Extensions.DependencyInjection;
namespace Falcon.DI.Test
{
[FalconDIRegister(typeof(MyClassWithDisable),Lifetime =ServiceLifetime.Transient)]
public class MyClassWithDisable:IDisposable
{
public static int Count { get; set; } = 0;
public MyClassWithDisable() => Count += 1;
public void Dispose() {
Count -= 1;
}
}
}

22
Falcon.DI.Test/NotFull.cs Normal file
View File

@ -0,0 +1,22 @@
namespace Falcon.DI.Test
{
public interface INfi1 { }
public interface INfi2 { }
[FalconDIRegister]
public class NotFull:INfi1
{
}
[FalconDIRegister(typeof(NotFullObj))]
public class NotFullObj
{
public INfi1 F1 { get; set; }
public INfi2 F2 { get; set; }
public NotFullObj(INfi1 f1,INfi2 f2=null) {
this.F1 = f1;
this.F2 = f2;
}
}
}

View File

@ -0,0 +1,11 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace Falcon.DI.Test
{
[FalconDIRegister]
class RegisterToSelf
{
}
}

View File

@ -0,0 +1,8 @@
namespace Falcon.DI.Test
{
[FalconDIRegister(Lifetime = ServiceLifetime.Singleton)]
class SingletonTest
{
public int Val { get; set; } = 0;
}
}

View File

@ -0,0 +1,17 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>netcoreapp2.2;NET461;netstandard2.0</TargetFrameworks>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
<Description>对.NET CORE进行扩展加入FalconDIRegisterAttribute特性进行服务注册。</Description>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(TargetFramework)|$(Platform)'=='Debug|netcoreapp2.2|AnyCPU'">
<DocumentationFile>C:\Documentation\develop\FalconCore\Falcon.DI\Falcon.DI.xml</DocumentationFile>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="2.2.0" />
</ItemGroup>
</Project>

45
Falcon.DI/Falcon.DI.xml Normal file
View File

@ -0,0 +1,45 @@
<?xml version="1.0"?>
<doc>
<assembly>
<name>Falcon.DI</name>
</assembly>
<members>
<member name="T:Falcon.DI.FalconDIRegisterAttribute">
<summary>
自动注册服务特性
</summary>
</member>
<member name="M:Falcon.DI.FalconDIRegisterAttribute.#ctor">
<summary>
默认注册到所有实现的基础接口
</summary>
</member>
<member name="M:Falcon.DI.FalconDIRegisterAttribute.#ctor(System.Type[])">
<summary>
注册到提供的服务类型
</summary>
<param name="type">服务类型</param>
</member>
<member name="P:Falcon.DI.FalconDIRegisterAttribute.ServiceTypes">
<summary>
注册的服务类型集合
</summary>
</member>
<member name="P:Falcon.DI.FalconDIRegisterAttribute.Lifetime">
<summary>
生命周期
</summary>
</member>
<member name="T:Falcon.DI.IServiceCollectionExtend">
<summary>
服务集合方法扩展
</summary>
</member>
<member name="M:Falcon.DI.IServiceCollectionExtend.UseFalconDI(Microsoft.Extensions.DependencyInjection.IServiceCollection,System.Reflection.Assembly[])">
<summary>
实现自动DI注册
</summary>
<param name="services">服务集合</param>
</member>
</members>
</doc>

View File

@ -0,0 +1,30 @@
using System;
namespace Falcon.DI
{
/// <summary>
/// 自动注册服务特性。如果要注册到特定服务可以指定,否则注册到所有实现的接口服务,如果未实现任何接口注册到类型本身。
/// </summary>
[AttributeUsage(AttributeTargets.Class)]
public class FalconDIRegisterAttribute:Attribute
{
/// <summary>
/// 默认注册到所有实现的基础接口
/// </summary>
public FalconDIRegisterAttribute() { }
/// <summary>
/// 注册到提供的服务类型
/// </summary>
/// <param name="type">服务类型</param>
public FalconDIRegisterAttribute(params Type[] type) => this.ServiceTypes = type;
/// <summary>
/// 注册的服务类型集合
/// </summary>
public Type[] ServiceTypes { get; set; } = null;
/// <summary>
/// 生命周期
/// </summary>
public ServiceLifetime Lifetime { get; set; } = ServiceLifetime.Scoped;
}
}

View File

@ -0,0 +1,15 @@
using System;
namespace Falcon.DI
{
/// <summary>
/// 依赖注入实例化工厂
/// </summary>
public interface IFalconDIInstantFactory<T>
{
/// <summary>
/// 通过给定容器实例化对象
/// </summary>
T Instance();
}
}

View File

@ -0,0 +1,48 @@
using System;
using System.Reflection;
using Microsoft.Extensions.DependencyInjection;
using msdi = Microsoft.Extensions.DependencyInjection;
namespace Falcon.DI
{
/// <summary>
/// 服务集合方法扩展
/// </summary>
public static class IServiceCollectionExtend
{
/// <summary>
/// 实现自动DI注册
/// </summary>
/// <param name="services">服务集合</param>
public static IServiceCollection UseFalconDI(this IServiceCollection services,params Assembly[] assemblies) {
if(assemblies == null || assemblies.Length == 0) {
return services.UseFalconDI(AppDomain.CurrentDomain.GetAssemblies());
}
foreach(Assembly ass in assemblies) {
foreach(Type type in ass.GetTypes()) {
var ra = type.GetCustomAttribute<FalconDIRegisterAttribute>(true);
if(ra != null) {
//如果未提供服务类型,注册到所有实现的接口
ra.ServiceTypes = ra.ServiceTypes ?? type.GetInterfaces();
//如果未实现任何接口,注册到类型本身
if(ra.ServiceTypes == null || ra.ServiceTypes.Length == 0) {
ra.ServiceTypes = new Type[] { type };
}
foreach(var ser in ra.ServiceTypes) {
services.Add(new ServiceDescriptor(ser,type,convertLifetime(ra.Lifetime)));
}
}
}
}
return services;
}
/// <summary>
/// 转换生存期枚举
/// </summary>
/// <param name="lt">生存期</param>
/// <returns></returns>
private static msdi.ServiceLifetime convertLifetime(ServiceLifetime lt) {
return (msdi.ServiceLifetime)(int)lt;
}
}
}

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
https://go.microsoft.com/fwlink/?LinkID=208121.
-->
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<PublishProtocol>FileSystem</PublishProtocol>
<Configuration>Release</Configuration>
<Platform>Any CPU</Platform>
<TargetFramework>netcoreapp2.2</TargetFramework>
<PublishDir>bin\Debug\netcoreapp2.2\publish\</PublishDir>
</PropertyGroup>
</Project>

View File

@ -0,0 +1,21 @@
namespace Falcon.DI
{
/// <summary>
/// 服务生存期
/// </summary>
public enum ServiceLifetime
{
/// <summary>
/// 单例
/// </summary>
Singleton = 0,
/// <summary>
/// 每个Scoped内单例
/// </summary>
Scoped = 1,
/// <summary>
/// 瞬时,每次返回不同的对象
/// </summary>
Transient = 2
}
}

View File

@ -0,0 +1,125 @@
using System.Collections.Generic;
using System.Data.Common;
using System.Data.SqlClient;
using System.Linq;
using System.Reflection;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
namespace Falcon.ModelSP
{
/// <summary>
/// 数据库上下文方法扩展
/// </summary>
public static class DataExtend
{
/// <summary>
/// 执行无返回值的存储过程
/// </summary>
/// <typeparam name="TPrarmType">参数类型</typeparam>
/// <param name="db">数据上下文</param>
/// <param name="data">参数数据</param>
public static int RunProcuder<TPrarmType>(this DbContext db,TPrarmType data) {
var parms = getParams(data);
return db.Database.ExecuteSqlCommand(getProcuderName<TPrarmType>(),parms.ToArray());
}
/// <summary>
/// 执行有返回值的存储过程
/// </summary>
/// <typeparam name="TPrarmType">参数类型</typeparam>
/// <typeparam name="TResultType">返回结果项类型</typeparam>
/// <param name="db">数据上下文</param>
/// <param name="data">参数数据</param>
public static IEnumerable<TResultType> RunProcuder<TPrarmType, TResultType>(this DbContext db,TPrarmType data)
where TResultType : class, new() {
var parms = getParams(data);
return db.Database.SqlQuery<TResultType>(getProcuderName<TPrarmType>(),parms.ToArray()).ToList();
}
/// <summary>
/// 获取存储过程参数枚举
/// </summary>
/// <typeparam name="T">参数模型类型</typeparam>
/// <param name="data">参数实例</param>
private static IEnumerable<SqlParameter> getParams<T>(T data) {
if(data == null)
yield break;
foreach(var p in typeof(T).GetProperties()) {
if(!p.CanRead || ignoreProp(p))
continue;
yield return new SqlParameter($"@{getName(p)}",p.GetValue(data));
}
}
/// <summary>
/// 是否忽略属性
/// </summary>
/// <param name="p">要检查的属性</param>
private static bool ignoreProp(PropertyInfo p) {
return p.GetCustomAttribute<FalconSPIgnoreAttribute>(true) != null;
}
/// <summary>
/// 获取存储过程参数名称
/// </summary>
/// <param name="p">对应的属性</param>
private static string getName(PropertyInfo p) {
var np = p.GetCustomAttribute<FalconSPPrarmNameAttribute>(true);
if(np != null && np is FalconSPPrarmNameAttribute na) {
return na.Name;
}
return p.Name;
}
/// <summary>
/// 获取存储过程名
/// </summary>
/// <typeparam name="T">参数模型</typeparam>
private static string getProcuderName<T>() {
var attr = typeof(T).GetCustomAttribute<FalconSPProcuderNameAttribute>(true);
if(attr != null && attr is FalconSPProcuderNameAttribute pna && !string.IsNullOrEmpty(pna.ProcuderName)) {
return pna.ProcuderName;
}
return typeof(T).Name;
}
/// <summary>
/// 根据传入的sql语句和参数枚举执行存储过程并且返回类型枚举
/// </summary>
/// <typeparam name="TR">返回值类型</typeparam>
/// <param name="db">数据库上下文</param>
/// <param name="sql">要执行的sql语句</param>
/// <param name="para">参数枚举</param>
/// <returns></returns>
public static IEnumerable<TR> SqlQuery<TR>(this DatabaseFacade db,string sql,params SqlParameter[] paras)
where TR : class, new() {
var connection = db.GetDbConnection();
using(var cmd = connection.CreateCommand()) {
cmd.CommandText = sql;
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddRange(paras);
connection.Open();
var dr = cmd.ExecuteReader();
var result = new List<TR>();
if(!dr.CanGetColumnSchema())
return result;
while(dr.Read()) {
var item = new TR();
var columnSchema = dr.GetColumnSchema();
for(var i = 0;i < columnSchema.Count;i++) {
var name = dr.GetName(i);
var value = dr.IsDBNull(i) ? null : dr.GetValue(i);
var pi = typeof(TR).GetProperty(name);
if(pi == null || !pi.CanWrite)
continue;
pi.SetValue(item,value);
}
result.Add(item);
}
connection.Close();
return result;
}
}
}
}

View File

@ -0,0 +1,12 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>netstandard2.0;NET461</TargetFrameworks>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="2.2.6" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="2.2.6" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,11 @@
using System;
namespace Falcon.ModelSP
{
/// <summary>
/// 表示调用时候忽略此属性
/// </summary>
public class FalconSPIgnoreAttribute:Attribute
{
}
}

View File

@ -0,0 +1,13 @@
using System;
namespace Falcon.ModelSP
{
/// <summary>
/// 定义名称
/// </summary>
public class FalconSPPrarmNameAttribute:Attribute
{
public FalconSPPrarmNameAttribute(string name) { this.Name = name; }
public string Name { get; set; }
}
}

View File

@ -0,0 +1,14 @@
using System;
namespace Falcon.ModelSP
{
/// <summary>
/// 定义存储过程名称
/// </summary>
public class FalconSPProcuderNameAttribute:Attribute
{
public string ProcuderName { get; set; }
public FalconSPProcuderNameAttribute(string m) => this.ProcuderName = m;
}
}

View File

@ -0,0 +1,45 @@
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.EntityFrameworkCore;
namespace Falcon.ModelSP
{
/// <summary>
/// 执行存储过程接口
/// </summary>
public interface IFalconSPRuner
{
/// <summary>
/// 通过数据库上下文执行无返回值的存储过程
/// </summary>
/// <typeparam name="TPrarmType">参数类型</typeparam>
/// <param name="db">数据上下文</param>
/// <param name="data">参数数据</param>
int RunSP<TPrarmType>(DbContext db,TPrarmType data);
/// <summary>
/// 通过数据库上下文执行存储过程,并返回查询结果
/// </summary>
/// <typeparam name="TPrarmType">参数类型</typeparam>
/// <typeparam name="TResultType">返回结果项类型</typeparam>
/// <param name="db">数据上下文</param>
/// <param name="data">参数数据</param>
IEnumerable<TResultType> RunSP<TPrarmType, TResultType>(DbContext db,TPrarmType data) where TResultType : class, new();
}
/// <summary>
/// 存储过程执行器实现
/// </summary>
public class FalconSPRuner:IFalconSPRuner
{
public int RunSP<TPrarmType>(DbContext db,TPrarmType data) {
return db.RunProcuder(data);
}
public IEnumerable<TResultType> RunSP<TPrarmType, TResultType>(DbContext db,TPrarmType data)
where TResultType : class, new() {
return db.RunProcuder<TPrarmType,TResultType>(data);
}
}
}

View File

@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Extensions.DependencyInjection;
namespace Falcon.ModelSP
{
/// <summary>
/// IServiceCollection扩展
/// </summary>
public static class IServiceCollectionExtend
{
/// <summary>
/// 注册对数据库存储过程模型化的调用扩展
/// </summary>
/// <param name="services">注册服务集合</param>
/// <returns></returns>
public static IServiceCollection UseFalconSP(this IServiceCollection services) {
return services.AddSingleton<IFalconSPRuner,FalconSPRuner>();
}
}
}

View File

@ -0,0 +1,12 @@
using System;
namespace Falcon.ModelSP
{
/// <summary>
/// 存储过程没有找到的异常
/// </summary>
public class ProcuderNotFoundException:Exception
{
public ProcuderNotFoundException() : base("存储过程没有找到") { }
}
}

67
FalconCore.sln Normal file
View File

@ -0,0 +1,67 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.29201.188
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Falcon.DI", "Falcon.DI\Falcon.DI.csproj", "{C32977BC-428C-4249-B115-0AE2A06149E5}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Falcon.DI.Test", "Falcon.DI.Test\Falcon.DI.Test.csproj", "{35BAAEAB-46D0-4265-8633-EB8063F769CF}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Falcon.Cache", "Falcon.Cache\Falcon.Cache.csproj", "{1B081C80-C3BF-4F78-A9AA-FF2E8A9EC627}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MS.ResidCache.Test", "MS.ResidCache.Test\MS.ResidCache.Test.csproj", "{9572943D-9960-4FAD-81F5-B2EBF9FE7338}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Falcon.Packget.Test", "Falcon.DI.Packget.Test\Falcon.Packget.Test.csproj", "{2BFA3AC6-5A87-4B2A-8487-AAE62A41FDE4}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Falcon.ModelSP", "Falcon.ModelSP\Falcon.ModelSP.csproj", "{D31D628F-60F5-4F98-8280-2D312B0A99F1}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Falcon.AutoTableLog", "Falcon.AutoTableLog\Falcon.AutoTableLog.csproj", "{61C50690-4419-4F6D-B34D-4258565185E9}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Falcon.AutoTableLog.Test", "Falcon.AutoTableLog.Test\Falcon.AutoTableLog.Test.csproj", "{D60683D5-D6F6-41EE-9627-43C34C977C45}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{C32977BC-428C-4249-B115-0AE2A06149E5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C32977BC-428C-4249-B115-0AE2A06149E5}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C32977BC-428C-4249-B115-0AE2A06149E5}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C32977BC-428C-4249-B115-0AE2A06149E5}.Release|Any CPU.Build.0 = Release|Any CPU
{35BAAEAB-46D0-4265-8633-EB8063F769CF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{35BAAEAB-46D0-4265-8633-EB8063F769CF}.Debug|Any CPU.Build.0 = Debug|Any CPU
{35BAAEAB-46D0-4265-8633-EB8063F769CF}.Release|Any CPU.ActiveCfg = Release|Any CPU
{35BAAEAB-46D0-4265-8633-EB8063F769CF}.Release|Any CPU.Build.0 = Release|Any CPU
{1B081C80-C3BF-4F78-A9AA-FF2E8A9EC627}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{1B081C80-C3BF-4F78-A9AA-FF2E8A9EC627}.Debug|Any CPU.Build.0 = Debug|Any CPU
{1B081C80-C3BF-4F78-A9AA-FF2E8A9EC627}.Release|Any CPU.ActiveCfg = Release|Any CPU
{1B081C80-C3BF-4F78-A9AA-FF2E8A9EC627}.Release|Any CPU.Build.0 = Release|Any CPU
{9572943D-9960-4FAD-81F5-B2EBF9FE7338}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{9572943D-9960-4FAD-81F5-B2EBF9FE7338}.Debug|Any CPU.Build.0 = Debug|Any CPU
{9572943D-9960-4FAD-81F5-B2EBF9FE7338}.Release|Any CPU.ActiveCfg = Release|Any CPU
{9572943D-9960-4FAD-81F5-B2EBF9FE7338}.Release|Any CPU.Build.0 = Release|Any CPU
{2BFA3AC6-5A87-4B2A-8487-AAE62A41FDE4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{2BFA3AC6-5A87-4B2A-8487-AAE62A41FDE4}.Debug|Any CPU.Build.0 = Debug|Any CPU
{2BFA3AC6-5A87-4B2A-8487-AAE62A41FDE4}.Release|Any CPU.ActiveCfg = Release|Any CPU
{2BFA3AC6-5A87-4B2A-8487-AAE62A41FDE4}.Release|Any CPU.Build.0 = Release|Any CPU
{D31D628F-60F5-4F98-8280-2D312B0A99F1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D31D628F-60F5-4F98-8280-2D312B0A99F1}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D31D628F-60F5-4F98-8280-2D312B0A99F1}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D31D628F-60F5-4F98-8280-2D312B0A99F1}.Release|Any CPU.Build.0 = Release|Any CPU
{61C50690-4419-4F6D-B34D-4258565185E9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{61C50690-4419-4F6D-B34D-4258565185E9}.Debug|Any CPU.Build.0 = Debug|Any CPU
{61C50690-4419-4F6D-B34D-4258565185E9}.Release|Any CPU.ActiveCfg = Release|Any CPU
{61C50690-4419-4F6D-B34D-4258565185E9}.Release|Any CPU.Build.0 = Release|Any CPU
{D60683D5-D6F6-41EE-9627-43C34C977C45}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D60683D5-D6F6-41EE-9627-43C34C977C45}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D60683D5-D6F6-41EE-9627-43C34C977C45}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D60683D5-D6F6-41EE-9627-43C34C977C45}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {ED64939B-E078-43FD-B716-81EFE00AB638}
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,17 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp2.2</TargetFramework>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="2.2.0" />
<PackageReference Include="Microsoft.Extensions.Caching.Redis.Core" Version="1.0.3" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.0.1" />
<PackageReference Include="MSTest.TestAdapter" Version="1.4.0" />
<PackageReference Include="MSTest.TestFramework" Version="1.4.0" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,32 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.Design;
using System.Text;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace MS.ResidCache.Test
{
[TestClass]
public class MS_MemeryCacheUnitTest
{
[TestMethod]
public void IDistributedCacheTestMethod() {
IMemoryCache cache = new MemoryCache(new MemoryCacheOptions {
});
var key = "mcut_a";
cache.Set(key,key);
var r = cache.Get(key);
Assert.AreEqual(r,key);
cache.Remove(key);
r = cache.Get(key);
Assert.IsNull(r);
if(cache is MemoryCache dis) {
dis.Dispose();
}
}
}
}

View File

@ -0,0 +1,29 @@
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.Extensions.Caching.Redis;
using Microsoft.Extensions.Caching.Distributed;
namespace MS.ResidCache.Test
{
[TestClass]
public class MicrosoftRedisCacheUnitTest
{
[TestMethod]
public void IDistributedCacheTestMethod1() {
IDistributedCache cache = new RedisCache(new RedisCacheOptions {
Configuration = "127.0.0.1:7001,password=123654",
InstanceName = "mcut",
});
var key = "mcut_a";
cache.SetString(key,key);
var r = cache.GetString(key);
Assert.AreEqual(r,key);
cache.Remove(key);
r = cache.GetString(key);
Assert.IsNull(r);
if(cache is RedisCache dis) {
dis.Dispose();
}
}
}
}