Autofac 服务未注册,但已注册
Autofac service not registered but it is
最近我在使用 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 模块。如果我在模块中放置一个断点,我会看到它被调用并注册了。此外,如果我检查容器注册,我会看到有 ICommonServices 的注册:
Activator = Object (DelegateActivator), Services = [Infrastructure.ICommonServices],
Lifetime = Autofac.Core.Lifetime.CurrentScopeLifetime, Sharing = None, Ownership = OwnedByLifetimeScope,
Pipeline = Autofac.Core.Pipeline.ResolvePipeline
如果我将注册从 AutofacModule 移出到主程序集,就在 builder.Build() 之前,那么一切正常,Autofac 能够解决它。
为什么注册了服务会报错?而且这不是唯一的。
问题是 .net core 3.1 中的程序集扫描。
旧的 - 非工作方式:
var assemblies= Assembly.GetExecutingAssembly()
.GetAllAssemblies()
.ToArray();
新的 - 工作中的:
var l2Assemblies = Assembly.GetExecutingAssembly()
.GetAllAssembliesWithContext()
.ToArray();
最近我在使用 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 模块。如果我在模块中放置一个断点,我会看到它被调用并注册了。此外,如果我检查容器注册,我会看到有 ICommonServices 的注册:
Activator = Object (DelegateActivator), Services = [Infrastructure.ICommonServices],
Lifetime = Autofac.Core.Lifetime.CurrentScopeLifetime, Sharing = None, Ownership = OwnedByLifetimeScope,
Pipeline = Autofac.Core.Pipeline.ResolvePipeline
如果我将注册从 AutofacModule 移出到主程序集,就在 builder.Build() 之前,那么一切正常,Autofac 能够解决它。
为什么注册了服务会报错?而且这不是唯一的。
问题是 .net core 3.1 中的程序集扫描。 旧的 - 非工作方式:
var assemblies= Assembly.GetExecutingAssembly()
.GetAllAssemblies()
.ToArray();
新的 - 工作中的:
var l2Assemblies = Assembly.GetExecutingAssembly()
.GetAllAssembliesWithContext()
.ToArray();