第一步
先下载关于Autofac的使用 <PackageReference Include="Autofac.Extensions.DependencyInjection" Version="6.0.0" /> 这里是6.0 的Netget包 直接引进程序集即可
第二部 创建一个.cs的类然后写方法
//重写Autofac管道Load方法
protected override void Load(ContainerBuilder builder1)
{
//程序集注入业务服务
var IAppSerVice = Assembly.Load("Smarthealthcare.Service");
var AppSerVice = Assembly.Load("Smarthealthcare.Service");
// builder1.RegisterAssemblyTypes(Assembly.LoadFrom("Smarthealthcare.Service")).AsImplementedInterfaces();
// builder1.RegisterAssemblyTypes(Assembly.GetExecutingAssembly()).AsImplementedInterfaces();
//根据名称约定(服务层)(服务层的接口和实现均以Service结尾),实现服务接口和服务实现的依赖
builder1.RegisterAssemblyTypes(IAppSerVice, AppSerVice).Where(x => x.Name.EndsWith("SerVice")).AsImplementedInterfaces().EnableInterfaceInterceptors();//
EnableInterfaceInterceptors//用于启用接口拦截器
}
注:在程序集注入服务中 引入你的程序集名称 例:Smarthealthcare.Service 就是我的程序集名称
然后再 把EndsWith里面的SerVice改为你定义的Service即可
第三步 在Program配置AUtofac
builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory()).ConfigureContainer<ContainerBuilder>(builder =>
{
builder.RegisterType<LogInterceptor>();//是用于注册日志拦截器的代码
builder.RegisterModule(new AutofacModuleRegister()); 在Autofac里面注册方法
//注册泛型基本仓储实现
builder.RegisterGeneric(typeof(Repository<,>)).As(typeof(IRepository<,>)).InstancePerDependency();
builder.RegisterGeneric(typeof(Repository<>)).As(typeof(IRepository<>)).InstancePerDependency();
});
日志拦截器配置
using Castle.DynamicProxy;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Extensions;
using Newtonsoft.Json;
using Smarthealthcare.Domain.Healthcare;
using Smarthealthcare.Dto;
using SqlSugar;
using System.Runtime.InteropServices;
namespace Smarthealthcare.Service
{
public class LogInterceptor : IInterceptor
{
private readonly ISqlSugarClient sqlSugar;
private readonly IHttpContextAccessor http;
public LogInterceptor(ISqlSugarClient sqlSugar, IHttpContextAccessor http)
{
this.sqlSugar = sqlSugar;
this.http = http;
}
public void Intercept(IInvocation invocation)
{
// 非异步方法直接执行
invocation.Proceed();
var t = invocation.ReturnValue;
#region 拿到浏览器参数和操作系统
OperatingSystem os = Environment.OSVersion;
var UrlData = os.Platform;
string osName = string.Empty;
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
osName = "Windows";
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
osName = "Linux";
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
osName = "macOS";
}
else
{
osName = "Unknown";
}
var urli = osName;
var ServicePack = os.ServicePack;
var p = http.HttpContext.Request.GetEncodedUrl();
#endregion
var resultProperty = invocation.ReturnValue.GetType().GetProperty("Result")?.GetValue(invocation.ReturnValue);
if (invocation.Method.Name == "GetLoginUser")
{
#region 登录日志
SmartLoginLog smartLogin = new SmartLoginLog();
//请求方法参数
var list = JsonConvert.SerializeObject(resultProperty).ToString();
var response = JsonConvert.DeserializeObject<ApiResponseDto>(list);
if (response.Data == null)
{
smartLogin.LoginUserName = "";
}
else
{
smartLogin.LoginUserName = response.Data.User_Name;
}
smartLogin.LoginRequestService = invocation.TargetType.FullName;
smartLogin.LoginMethodName = invocation.Method.Name;
smartLogin.LoginHttpType = http.HttpContext.Request.Method;
var parameters = invocation.Method.GetParameters();
var arguments = invocation.Arguments;
List<string> parameterStrings = new List<string>();
for (int i = 0; i < parameters.Length; i++)
{
var parameterName = JsonConvert.SerializeObject(parameters[i].Name);
var argumentValue = JsonConvert.SerializeObject(arguments[i]);
parameterStrings.Add(parameterName + ":" + argumentValue);
}
var result = string.Join(",", parameterStrings);
//请求参数
smartLogin.LoginHttpRequestParms = result.ToString();
smartLogin.LoginResultData = JsonConvert.SerializeObject(resultProperty).ToString();
smartLogin.RequestTime = DateTime.Now;
smartLogin.LoMessage = response.Message;
sqlSugar.Insertable(smartLogin).ExecuteReturnSnowflakeId();//单条插入返回雪花ID
#endregion
}
else
{
#region 操作日志
SmartLogest smartLog = new SmartLogest();
//请求方法参数
smartLog.RequestService = invocation.TargetType.FullName;
//请求人名称
//smartLog.ResultData =
smartLog.RequestUserName = http.HttpContext.User.Identity.Name;
smartLog.HttpType = http.HttpContext.Request.Method;
smartLog.ResultData = JsonConvert.SerializeObject(resultProperty).ToString();
//请求方法名称
smartLog.MethodName = invocation.Method.Name;
if (http.HttpContext.User?.Identity?.IsAuthenticated == true)
{
var claims = http.HttpContext.User.Identities.First().Claims.ToList();
if (claims.Count >= 3)
{
smartLog.RequestRoleName = claims[2].Value;
//其他逻辑...
}
else
{
//处理索引超出范围的错误情况
}
}
else
{
//处理用户未进行身份认证的情况
}
//请求参数方法
var parameters = invocation.Method.GetParameters();
var arguments = invocation.Arguments;
List<string> parameterStrings = new List<string>();
for (int i = 0; i < parameters.Length; i++)
{
var parameterName = JsonConvert.SerializeObject(parameters[i].Name);
var argumentValue = JsonConvert.SerializeObject(arguments[i]);
parameterStrings.Add(parameterName + ":" + argumentValue);
}
var result = string.Join(",", parameterStrings);
//请求参数
smartLog.HttpRequestParms = result.ToString();
//请求时间
smartLog.RequestTime = DateTime.Now;
//添加日志记录
sqlSugar.Insertable(smartLog).ExecuteReturnSnowflakeId();//单条插入返回雪花ID
#endregion
}
}
}
}
注:这里我已经写完 复制替换即可