We are building Authorization filter using Autofac's IAutofacAuthorizationFilter, we have register this filter in startup with our base controller. All controller inherit from our base controller. We have requirement in our execution to identify whether target contoller is registered with CustomAuthFilter. I tried using Reflection to check whether controller is registered CustomAuthFilter, I'm unable to get. Is their any better way to check controller is registered with 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();
This approach is using RegisterBuildCallback
event to filter the registrations. It's also using reflection because metadata types are not present on compile time or I'm not able to find. You may spend some time to refine the selection but this is the place where information is stored in container.
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));
});