我们正在使用Autofac的IAutofacAuthorizationFilter构建授权过滤器,我们已经在基本控制器启动时注册了该过滤器。所有控制器都继承自我们的基本控制器。在执行过程中,我们需要确定目标contoller是否已向CustomAuthFilter注册。我尝试使用反射来检查控制器是否已注册CustomAuthFilter,但无法获取。他们是否有更好的方法检查控制器是否已向CustomAuthFilter注册。
builder.RegisterType<CustomAuthFilter>()
.Named<IAutofacAuthorizationFilter>("CustomAuthFilter")
.WithParameters(new[]
{
new ResolvedParameter((pi, ctx) => pi.ParameterType == typeof(Logger),
(pi, ctx) => ctx.Resolve<Logger>()),
new ResolvedParameter((pi, ctx) => pi.ParameterType == typeof(Reader),
(pi, ctx) => ctx.Resolve<Reader>())
}
).AsWebApiAuthorizationFilterFor<ControllerBaseAPI>()
.InstancePerRequest();
答案 0 :(得分:1)
此方法使用RegisterBuildCallback
事件来过滤注册。由于元数据类型在编译时不存在或无法找到,因此也使用了反射。您可能需要花费一些时间来优化选择,但这是将信息存储在容器中的地方。
builder.RegisterBuildCallback(builtContainer =>
{
//Contains all controller registered with AutofacWebApiAuthorizationFilter
var registeredWithFilter = builtContainer.ComponentRegistry.Registrations.SelectMany(x => x.Metadata).Where(x => x.Key.Equals("AutofacWebApiAuthorizationFilter"))
.Select(x => x.Value).Select(x => x.GetType().GetProperty("ControllerType").GetValue(x))
.Select(x => x.GetType().GetProperty("Name").GetValue(x));
});