完成基础代码

This commit is contained in:
falcon 2019-12-27 11:39:10 +08:00
commit b624a8920a
18 changed files with 835 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,14 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace Falcon.DI.Test
{
[FalconDIRegister]
public abstract class AbstractWithDi
{
public AbstractWithDi() { }
}
public class ClassFromAbstractWithDi:AbstractWithDi { }
}

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

@ -0,0 +1,135 @@
using System.Linq;
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(this.GetType().Assembly);
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(this.GetType().Assembly);
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(this.GetType().Assembly);
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(this.GetType().Assembly);
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(this.GetType().Assembly);
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(this.GetType().Assembly);
//单例。两次获取为同一对象
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);
}
}
/// <summary>
/// 测试虚类不能注册
/// </summary>
[TestMethod]
public void AbstractTest() {
IServiceCollection ser = new ServiceCollection();
ser.UseFalconDI(this.GetType().Assembly);
using(var pd = ser.BuildServiceProvider()) {
var obj = pd.GetService<AbstractWithDi>();
System.Console.WriteLine(obj.GetType().FullName);
Assert.IsNotNull(obj);
var cla = obj as ClassFromAbstractWithDi;
Assert.IsNotNull(cla);
}
}
}
}

View File

@ -0,0 +1,20 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>netcoreapp3.1;netcoreapp3.0</TargetFrameworks>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="3.1.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.4.0" />
<PackageReference Include="MSTest.TestAdapter" Version="2.0.0" />
<PackageReference Include="MSTest.TestFramework" Version="2.0.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]
public class RegisterToSelf
{
}
}

View File

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

31
Falcon.DI.sln Normal file
View File

@ -0,0 +1,31 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.29613.14
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Falcon.DI", "Falcon.DI\Falcon.DI.csproj", "{896E75AF-6E5D-4FBE-954A-901743A0CBEF}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Falcon.DI.Test", "Falcon.DI.Test\Falcon.DI.Test.csproj", "{09D91A95-46AB-4461-9486-E45530FB9CA8}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{896E75AF-6E5D-4FBE-954A-901743A0CBEF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{896E75AF-6E5D-4FBE-954A-901743A0CBEF}.Debug|Any CPU.Build.0 = Debug|Any CPU
{896E75AF-6E5D-4FBE-954A-901743A0CBEF}.Release|Any CPU.ActiveCfg = Release|Any CPU
{896E75AF-6E5D-4FBE-954A-901743A0CBEF}.Release|Any CPU.Build.0 = Release|Any CPU
{09D91A95-46AB-4461-9486-E45530FB9CA8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{09D91A95-46AB-4461-9486-E45530FB9CA8}.Debug|Any CPU.Build.0 = Debug|Any CPU
{09D91A95-46AB-4461-9486-E45530FB9CA8}.Release|Any CPU.ActiveCfg = Release|Any CPU
{09D91A95-46AB-4461-9486-E45530FB9CA8}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {B6456D19-8A99-411A-AC5C-FF0B15873EEB}
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,20 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>NET461;netstandard2.0;netstandard2.1</TargetFrameworks>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
<Description>对.NET CORE进行扩展加入FalconDIRegisterAttribute特性进行服务注册。</Description>
<Version>1.0.2</Version>
<PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance>
<Authors>Falcon</Authors>
<Company>Falcon</Company>
<DocumentationFile>bin\$(Configuration)\$(TargetFramework)\$(AssemblyName).xml</DocumentationFile>
<PackageProjectUrl>http://39.105.71.191/Falcon/Falcon.Di</PackageProjectUrl>
<RepositoryUrl>http://39.105.71.191/Falcon/Falcon.Di</RepositoryUrl>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="3.1.0" />
</ItemGroup>
</Project>

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,75 @@
using System;
using System.Reflection;
using Microsoft.Extensions.DependencyInjection;
using msdi = Microsoft.Extensions.DependencyInjection;
using System.Linq;
using System.Collections.Generic;
namespace Falcon.DI
{
/// <summary>
/// 服务集合方法扩展
/// </summary>
public static class IServiceCollectionExtend
{
/// <summary>
/// 实现自动DI注册
/// </summary>
/// <param name="services">服务集合</param>
/// <param name="assemblies">要注册的程序集集合如果未指定则为CurrentDomain所有引入的程序集</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()) {
if(!type.CanInstance()) {
continue;
}
var ra = type.GetCustomAttribute<FalconDIRegisterAttribute>(true);
if(ra != null) {
//如果未提供服务类型,注册到所有实现的接口和基类
if(ra.ServiceTypes == null || ra.ServiceTypes.Length == 0) {
var sts = new List<Type>();
//添加所有实现的接口
sts.AddRange(type.GetInterfaces());
//添加非object基类
var baseType = type.BaseType;
if(baseType != typeof(object)) {
sts.Add(baseType);
}
//添加类型本身
sts.Add(type);
ra.ServiceTypes = sts.ToArray();
}
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;
}
/// <summary>
/// 获取类型是否可以实例化。
/// </summary>
/// <param name="type">类型</param>
/// <returns>是否可实例化</returns>
public static bool CanInstance(this Type type) {
if(!type.IsClass || type.IsAbstract) {
return false;
}
return true;
}
}
}

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
}
}

60
Readme.md Normal file
View File

@ -0,0 +1,60 @@
**使用说明**
1. 安装可以通过下载源码安装也可以通过nuget包安装。
1. 引入名字空间
~~~
using Microsoft.Extensions.DependencyInjection;
using Falcon.DI
~~~
1. 初始化容器使用UseFalconDI方法注册所有服务。
~~~
IServiceCollection ser = new ServiceCollection();
ser.UseFalconDI();
~~~
1. 添加注册特性,服务可以注册到基础接口或自身。
~~~
public interface IMyInterface
{
string Getname();
}
[FalconDIRegister]
public class MyClassInterfaces:IMyInterface
{
public string Getname() {
return this.GetType().Name;
}
}
~~~
1. 注入可以使用ServiceCollection获取注册的服务。
~~~
using(var pd = ser.BuildServiceProvider()) {
var service = pd.GetServices<IMyInterface>();
// Do something
}
~~~
或者使用构造注入
~~~
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;
}
}
~~~
以上例子中首先注入了NotFull类型实现INfi1服务然后又注册了NotFullObj类型并通过构造注入方式消费了INfi1服务。INfi2因为没有注册所以使用默认值跳过注入。