autofacautofac-module

Autofac service not registered but it is


Lately I have some issues with Autofac.

I have an aggregate service like this:

public interface ICommonServices
{
    IQueryBus QueryBus { get; }
    ICommandBus CommandBus { get; }
    INotificationBus NotificationBus { get; }
    ILoggerFactory LoggerFactory { get; }
    
}

And I am registering it like this:

public class AutofacModule : Module
{
    protected override void Load(ContainerBuilder builder)
    {
        builder.RegisterAggregateService<ICommonServices>();            
    }
}

And when I do:

var services = container.Resolve<ICommonServices>();

I am getting this error:

"The requested service 'Infrastructure.ICommonServices' has not been registered. 
 To avoid this exception, either register a component to provide the service, check for service 
 registration using IsRegistered(), or use the ResolveOptional() method to resolve an optional dependency."

I have many assemblies and I use Autofac modules. If I put a breakpoint in the module I see that it is called and registered. Also if I inspect Container registrations, I see that there is a registration for ICommonServices:

Activator = Object (DelegateActivator), Services = [Infrastructure.ICommonServices], 
 Lifetime = Autofac.Core.Lifetime.CurrentScopeLifetime, Sharing = None, Ownership = OwnedByLifetimeScope, 
 Pipeline = Autofac.Core.Pipeline.ResolvePipeline

If I move the registration out from AutofacModule to the main assembly, jst before the builder.Build() then all works and Autofac is abble to resolve it.

Why then the error if the service is registered? And this is not the only one.


Solution

  • The issue was Assembly scanning in .net core 3.1. The old - non working way:

    var assemblies= Assembly.GetExecutingAssembly()
                .GetAllAssemblies()
                .ToArray();
    

    the new - WORKING one:

    var l2Assemblies = Assembly.GetExecutingAssembly()
                .GetAllAssembliesWithContext()
                .ToArray();