Skip to content

Commit 6a75c5e

Browse files
committed
Simplify the startup. Cs
简化startup.cs,做封装
1 parent d7eb88a commit 6a75c5e

5 files changed

Lines changed: 174 additions & 149 deletions

File tree

Blog.Core/Blog.Core.xml

Lines changed: 5 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
using Autofac;
2+
using Autofac.Extras.DynamicProxy;
3+
using Blog.Core.AOP;
4+
using Blog.Core.Common;
5+
using log4net;
6+
using System;
7+
using System.Collections.Generic;
8+
using System.IO;
9+
using System.Reflection;
10+
11+
namespace Blog.Core.Extensions
12+
{
13+
public class AutofacModuleRegister : Autofac.Module
14+
{
15+
private static readonly ILog log = LogManager.GetLogger(typeof(AutofacModuleRegister));
16+
protected override void Load(ContainerBuilder builder)
17+
{
18+
var basePath = AppContext.BaseDirectory;
19+
//builder.RegisterType<AdvertisementServices>().As<IAdvertisementServices>();
20+
21+
22+
#region 带有接口层的服务注入
23+
24+
var servicesDllFile = Path.Combine(basePath, "Blog.Core.Services.dll");
25+
var repositoryDllFile = Path.Combine(basePath, "Blog.Core.Repository.dll");
26+
27+
if (!(File.Exists(servicesDllFile) && File.Exists(repositoryDllFile)))
28+
{
29+
var msg = "Repository.dll和service.dll 丢失,因为项目解耦了,所以需要先F6编译,再F5运行,请检查 bin 文件夹,并拷贝。";
30+
log.Error(msg);
31+
throw new Exception(msg);
32+
}
33+
34+
35+
36+
// AOP 开关,如果想要打开指定的功能,只需要在 appsettigns.json 对应对应 true 就行。
37+
var cacheType = new List<Type>();
38+
if (Appsettings.app(new string[] { "AppSettings", "RedisCachingAOP", "Enabled" }).ObjToBool())
39+
{
40+
builder.RegisterType<BlogRedisCacheAOP>();
41+
cacheType.Add(typeof(BlogRedisCacheAOP));
42+
}
43+
if (Appsettings.app(new string[] { "AppSettings", "MemoryCachingAOP", "Enabled" }).ObjToBool())
44+
{
45+
builder.RegisterType<BlogCacheAOP>();
46+
cacheType.Add(typeof(BlogCacheAOP));
47+
}
48+
if (Appsettings.app(new string[] { "AppSettings", "TranAOP", "Enabled" }).ObjToBool())
49+
{
50+
builder.RegisterType<BlogTranAOP>();
51+
cacheType.Add(typeof(BlogTranAOP));
52+
}
53+
if (Appsettings.app(new string[] { "AppSettings", "LogAOP", "Enabled" }).ObjToBool())
54+
{
55+
builder.RegisterType<BlogLogAOP>();
56+
cacheType.Add(typeof(BlogLogAOP));
57+
}
58+
59+
// 获取 Service.dll 程序集服务,并注册
60+
var assemblysServices = Assembly.LoadFrom(servicesDllFile);
61+
builder.RegisterAssemblyTypes(assemblysServices)
62+
.AsImplementedInterfaces()
63+
.InstancePerDependency()
64+
.EnableInterfaceInterceptors()//引用Autofac.Extras.DynamicProxy;
65+
.InterceptedBy(cacheType.ToArray());//允许将拦截器服务的列表分配给注册。
66+
67+
// 获取 Repository.dll 程序集服务,并注册
68+
var assemblysRepository = Assembly.LoadFrom(repositoryDllFile);
69+
builder.RegisterAssemblyTypes(assemblysRepository)
70+
.AsImplementedInterfaces()
71+
.InstancePerDependency();
72+
73+
#endregion
74+
75+
#region 没有接口层的服务层注入
76+
77+
//因为没有接口层,所以不能实现解耦,只能用 Load 方法。
78+
//注意如果使用没有接口的服务,并想对其使用 AOP 拦截,就必须设置为虚方法
79+
//var assemblysServicesNoInterfaces = Assembly.Load("Blog.Core.Services");
80+
//builder.RegisterAssemblyTypes(assemblysServicesNoInterfaces);
81+
82+
#endregion
83+
84+
#region 没有接口的单独类,启用class代理拦截
85+
86+
//只能注入该类中的虚方法,且必须是public
87+
//这里仅仅是一个单独类无接口测试,不用过多追问
88+
//builder.RegisterAssemblyTypes(Assembly.GetAssembly(typeof(Love)))
89+
// .EnableClassInterceptors()
90+
// .InterceptedBy(cacheType.ToArray());
91+
#endregion
92+
93+
#region 单独注册一个含有接口的类,启用interface代理拦截
94+
95+
//不用虚方法
96+
//builder.RegisterType<AopService>().As<IAopService>()
97+
// .AsImplementedInterfaces()
98+
// .EnableInterfaceInterceptors()
99+
// .InterceptedBy(typeof(BlogCacheAOP));
100+
#endregion
101+
102+
}
103+
}
104+
}

Blog.Core/Middlewares/AllServicesMildd.cs

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,9 @@
33
using Microsoft.Extensions.DependencyInjection;
44
using System;
55
using System.Collections.Generic;
6+
using System.IO;
67
using System.Linq;
8+
using System.Reflection;
79

810
namespace Blog.Core.Extensions
911
{
@@ -12,10 +14,14 @@ namespace Blog.Core.Extensions
1214
/// </summary>
1315
public static class AllServicesMildd
1416
{
15-
public static void UseAllServicesMildd(this IApplicationBuilder app, IServiceCollection _services, List<Type> tsDIAutofac)
17+
public static void UseAllServicesMildd(this IApplicationBuilder app, IServiceCollection _services)
1618
{
1719
if (app == null) throw new ArgumentNullException(nameof(app));
1820

21+
List<Type> tsDIAutofac = new List<Type>();
22+
tsDIAutofac.AddRange(Assembly.LoadFrom(Path.Combine(AppContext.BaseDirectory, "Blog.Core.Services.dll")).GetTypes().ToList());
23+
tsDIAutofac.AddRange(Assembly.LoadFrom(Path.Combine(AppContext.BaseDirectory, "Blog.Core.Repository.dll")).GetTypes().ToList());
24+
1925
app.Map("/allservices", builder => builder.Run(async context =>
2026
{
2127
context.Response.ContentType = "text/html; charset=utf-8";
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
using Blog.Core.Common;
2+
using log4net;
3+
using Microsoft.AspNetCore.Builder;
4+
using System;
5+
using System.IO;
6+
using System.Linq;
7+
using static Blog.Core.SwaggerHelper.CustomApiVersion;
8+
9+
namespace Blog.Core.Extensions
10+
{
11+
/// <summary>
12+
/// Cors 启动服务
13+
/// </summary>
14+
public static class SwaggerMildd
15+
{
16+
private static readonly ILog log = LogManager.GetLogger(typeof(SwaggerMildd));
17+
public static void UseSwaggerMildd(this IApplicationBuilder app, Func<Stream> streamHtml)
18+
{
19+
if (app == null) throw new ArgumentNullException(nameof(app));
20+
21+
app.UseSwagger();
22+
app.UseSwaggerUI(c =>
23+
{
24+
//根据版本名称倒序 遍历展示
25+
var ApiName = Appsettings.app(new string[] { "Startup", "ApiName" });
26+
typeof(ApiVersions).GetEnumNames().OrderByDescending(e => e).ToList().ForEach(version =>
27+
{
28+
c.SwaggerEndpoint($"/swagger/{version}/swagger.json", $"{ApiName} {version}");
29+
});
30+
31+
// 将swagger首页,设置成我们自定义的页面,记得这个字符串的写法:{项目名.index.html}
32+
if (streamHtml.Invoke() == null)
33+
{
34+
var msg = "index.html的属性,必须设置为嵌入的资源";
35+
log.Error(msg);
36+
throw new Exception(msg);
37+
}
38+
c.IndexStream = streamHtml;
39+
40+
41+
// 路径配置,设置为空,表示直接在根域名(localhost:8001)访问该文件,注意localhost:8001/swagger是访问不到的,去launchSettings.json把launchUrl去掉,如果你想换一个路径,直接写名字即可,比如直接写c.RoutePrefix = "doc";
42+
c.RoutePrefix = "";
43+
});
44+
}
45+
}
46+
}

0 commit comments

Comments
 (0)