I'm creating some authorization policies for ASP.NET Core and obviously I've created some AuthorizationHandlers.
Now, authorization mechanism requires authorization handlers to be resolvable. I'm using Autofac instead of built-in mechanism so here's how I'm trying to achieve it:
builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly())
.AsClosedTypesOf(typeof(AuthorizationHandler<>))
.As<IAuthorizationHandler>()
.OnActivating(x => System.Diagnostics.Debug.WriteLine(x.Instance))
.AutoActivate();
My understanding is:
I've added OnActivating and AutoActivate event for the purpose of debugging. As you can see I'm logging when there's an activation.
But my logging doesn't execute even once. It seems that Autofac is not able to find my authorization handlers. How to fix it?
The code you posted looks perfect. Anyway, I've tested it and works for me as expected (including auto-activate). Environment: NET Core 2.1, Autofac.Extensions.DependencyInjection 4.2.2.
I'm 99,9% sure the problem is elsewhere. I can think of the following:
Does your Startup.ConfigureServices method look like this?
public IServiceProvider ConfigureServices(IServiceCollection services)
{
// standard ASP.NET Core setup like
services.AddMvc(...)
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
var builder = new ContainerBuilder();
builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly())
.AsClosedTypesOf(typeof(AuthorizationHandler<>))
.As<IAuthorizationHandler>()
.OnActivating(x => System.Diagnostics.Debug.WriteLine(x.Instance))
.AutoActivate();
builder.Populate(services);
var container = builder.Build();
return new AutofacServiceProvider(container);
}