.Net 6 + AspectCore 2.2.0
Program.cs中使用AspectCore
在拦截器工厂中的IServiceProvider
与测试类中的IServiceProvider
并不是同一个实例,导致,在AOP中无法获取到本次连接所有的相关信息,请大家不吝赐教
//替换默认的容器
builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
services.ConfigureDynamicProxy(config =>
{
config.Interceptors.Add(new LogAopFactory());
config.NonAspectPredicates.Add(m => m.CustomAttributes.All(a => a.AttributeType != typeof(LogInfoAttribute)));
});
获取拦截器的工厂
public class LogAopFactory : InterceptorFactory
{
public override IInterceptor CreateInstance(IServiceProvider serviceProvider)
{
Console.WriteLine($"CustomFactory {serviceProvider.GetType().FullName} {serviceProvider.GetHashCode()} ");
return serviceProvider.GetService<LogAop>()!;
}
}
在组件中注入的测试类
public class StoreTest
{
private readonly IServiceProvider serviceProvider;
public StoreTest(IServiceProvider serviceProvider)
{
Console.WriteLine($"provider {serviceProvider.GetType().FullName} {serviceProvider.GetHashCode()}");
var store = serviceProvider.GetRequiredService<UserStore>();
this.serviceProvider = serviceProvider;
Console.WriteLine($"StoreTest {store.GetHashCode()}");
}
}
建议检查一下 CreateInstance(IServiceProvider serviceProvider)
中的 serviceProvider
从何而来