最近我对Autofac有一些问题。
我有一个这样的聚合服务:
public interface ICommonServices
{
IQueryBus QueryBus { get; }
ICommandBus CommandBus { get; }
INotificationBus NotificationBus { get; }
ILoggerFactory LoggerFactory { get; }
}
我是这样注册的:
public class AutofacModule : Module
{
protected override void Load(ContainerBuilder builder)
{
builder.RegisterAggregateService<ICommonServices>();
}
}
当我这样做的时候:
var services = container.Resolve<ICommonServices>();
我得到这个错误:
"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."
我有很多程序集,我使用Autofac模块。如果我在模块中放置一个断点,我会看到它被调用并注册。此外,如果我检查Container注册,我会发现有ICommonServices:的注册
Activator = Object (DelegateActivator), Services = [Infrastructure.ICommonServices],
Lifetime = Autofac.Core.Lifetime.CurrentScopeLifetime, Sharing = None, Ownership = OwnedByLifetimeScope,
Pipeline = Autofac.Core.Pipeline.ResolvePipeline
如果我将注册从AutofacModule移到主程序集,则在生成器之前执行jst。Build((,然后所有工作,Autofac可以解决它。
如果服务已注册,为什么会出现错误?这并不是唯一一个。
问题是.net核心3.1中的程序集扫描。旧的非工作方式:
var assemblies= Assembly.GetExecutingAssembly()
.GetAllAssemblies()
.ToArray();
新的-正在工作的一个:
var l2Assemblies = Assembly.GetExecutingAssembly()
.GetAllAssembliesWithContext()
.ToArray();