Azure Service Fabric中Autofac IoC配置:如何无参实例化Mapper?
解决Azure Service Fabric有状态服务中Mapper实例化的依赖注入问题
你的问题根源很清晰:你没有把Mapper类注册到Autofac容器中,而是手动用new Mapper()创建实例,这就导致Autofac无法自动为它注入所需的仓储依赖,所以会抛出缺少参数的错误。下面是具体的解决步骤:
步骤1:将Mapper注册到Autofac容器
在你的GlobalAutofacModule中,添加Mapper的注册代码。因为Mapper的构造函数依赖的所有仓储接口已经在容器中注册过了,Autofac会自动帮你解析这些依赖:
public class GlobalAutofacModule : Module { protected override void Load(ContainerBuilder builder) { // 已有的仓储注册代码保持不变 builder.RegisterType<ChargeRepository>().As<IChargeRepository>().SingleInstance(); builder.RegisterType<CustomerRepository>().As<ICustomerRepository>().SingleInstance(); builder.RegisterType<InvoiceItemRepository>().As<IInvoiceItemRepository>().SingleInstance(); builder.RegisterType<PlanRepository>().As<IPlanRepository>().SingleInstance(); builder.RegisterType<ProductRepository>().As<IProductRepository>().SingleInstance(); builder.RegisterType<SourceRepository>().As<ISourceRepository>().SingleInstance(); builder.RegisterType<SubscriptionRepository>().As<ISubscriptionRepository>().SingleInstance(); builder.RegisterType<TokenRepository>().As<ITokenRepository>().SingleInstance(); // 添加Mapper的注册,可根据需求选择生命周期(比如InstancePerLifetimeScope或SingleInstance) builder.RegisterType<Mapper>().InstancePerLifetimeScope(); } }
步骤2:通过构造函数注入Mapper到你的服务中
在Payment服务的构造函数中添加Mapper的依赖,让Autofac自动注入它,这样你在服务方法里就可以直接使用,不需要手动实例化:
private readonly Mapper _mapper; public Payment(StatefulServiceContext context, IChargeRepository chargeRepo, ICustomerRepository customerRepo, IInvoiceItemRepository invoiceItemRepo, IPlanRepository planRepository, IProductRepository productRepo, ISourceRepository sourceRepo, ISubscriptionRepository subscriptionRepo, ITokenRepository tokenRepo, Mapper mapper) : base(context) { _chargeRepo = chargeRepo; // 其他仓储的赋值代码保持不变 _mapper = mapper; }
步骤3:在服务方法中直接使用注入的Mapper
现在你可以在服务的任意方法里直接调用_mapper的方法,不需要手动传参:
var test = _mapper.GetProductsDto(false, false);
关于你的临时解决方案的调整
如果你想保留单例容器的方式(比如某些场景下需要手动从容器解析),需要确保:
Mapper已经在容器中注册(即步骤1中的代码)- 从容器解析
Mapper实例,而不是手动new:
// 在服务方法中 var mapper = ContainerOperations.Container.Resolve<Mapper>(); var test = mapper.GetProductsDto(false, false);
不过更推荐构造函数注入的方式,这是IoC的最佳实践,它能让依赖关系更清晰,也更容易进行单元测试。
内容的提问来源于stack exchange,提问作者Xav Sc
相关产品推荐
相关产品推荐

