autoFac无法解析构造函数的参数服务范围' void

发布于 2025-01-22 09:07:37 字数 8 浏览 3 评论 0原文

continue

I get the following error when I try to inject IServiceScopeFactory in a class in my business layer: "Cannot resolve parameter 'Microsoft.Extensions.DependencyInjection.IServiceScopeFactory serviceScopeFactory' of constructor 'Void"

I havent worked with AutoFac before so I am wondering what I am missing:

This is my code:

private static void ConfigureAutoFacIoC(ContainerBuilder builder, HttpConfiguration config, IAppBuilder app)
    {
        AutoFacRegister.RegisterDependency(builder, Assembly.GetExecutingAssembly());
        RegisterWebApiDependency(builder);

        builder.RegisterWebApiFilterProvider(config);
        var container = builder.Build();
        // Set the dependency resolver to be Autofac.
        config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
        app.UseAutofacMiddleware(container);
        app.UseAutofacWebApi(config);
    }

public static class AutoFacRegister
{
    public static void RegisterDependency(ContainerBuilder builder, Assembly webApiAssembly)
    {
        RegisterDataLayer(builder);
        RegisterBusinessLayer(builder);
        RegisterShared(builder);
        RegisterPresentationLayer(builder, webApiAssembly);
    }

    private static void RegisterDataLayer(ContainerBuilder builder)
    {
        builder.RegisterType<SBSContext>().InstancePerLifetimeScope();
        builder.RegisterType<AgdaContext>().InstancePerLifetimeScope();
        builder.RegisterType<MailingRepository>().As<IMailingRepository>();
        builder.RegisterType<MembershipRepository>().As<IMembershipRepository>();
        builder.RegisterType<CourseMomentRepository>().As<ICourseMomentRepository>();
        builder.RegisterType<MedalRepository>().As<IMedalRepository>();
        builder.RegisterType<PersonRepository>().As<IPersonRepository>();
        builder.RegisterType<CourseRepository>().As<ICourseRepository>();
        builder.RegisterType<OrganisationRepository>().As<IOrganisationRepository>();
        builder.RegisterType<FunctionRepository>().As<IFunctionRepository>();
        builder.RegisterType<PaymentRepository>().As<IPaymentRepository>();
        builder.RegisterType<ChargeCategoryRepository>().As<IChargeCategoryRepository>();
        builder.RegisterType<OutcodeRepository>().As<IOutcodeRepository>();
        builder.RegisterType<UserRepository>().As<IUserRepository>();
        builder.RegisterType<ViewPersonRepository>().As<IViewPersonRepository>();
        builder.RegisterType<AgdaRepository>().As<IAgdaRepository>();
        builder.RegisterType<ReportRepository>().As<IReportRepository>();
        builder.RegisterType<ReportManager>().As<IReportManager>();
        builder.RegisterType<CourseApplicationRepository>().As<ICourseApplicationRepository>();
        builder.RegisterType<RepdayRepository>().As<IRepdayRepository>();
        builder.RegisterType<ChargeCategoryRepository>().As<IChargeCategoryRepository>();
        builder.RegisterType<CommuneRepository>().As<ICommuneRepository>();
        builder.RegisterType<PapApiAmbassador>().As<IPapApiAmbassador>();
        builder.RegisterType<VolenteerRepository>().As<IVolenteerRepository>();
        builder.RegisterType<AgreementTypeRepository>().As<IAgreementTypeRepository>();
        builder.RegisterType<CourseMomentStatusRepository>().As<ICourseMomentStatusRepository>();
        builder.RegisterType<CourseTypeRepository>().As<ICourseTypeRepository>();
        builder.RegisterType<AttestationRepository>().As<IAttestationRepository>();

        builder.RegisterGeneric(typeof(GenericRepository<,>)).As(typeof(IGenericRepository<,>));

    }

    private static void RegisterBusinessLayer(ContainerBuilder builder)
    {
        var bllAssembly = AppDomain.CurrentDomain.GetAssemblies().
            SingleOrDefault(assembly => assembly.GetName().Name == "SBS.Ferdinand.BusinessLayer");

        builder.RegisterAssemblyTypes(typeof(IServiceScopeFactory).Assembly).As<IServiceScopeFactory>();

        builder.RegisterAssemblyTypes(bllAssembly)
            .Where(x => x.Name.EndsWith("Handler"))
            .AsImplementedInterfaces();

        builder.RegisterAssemblyTypes(bllAssembly)
            .Where(x => x.Name.EndsWith("Helper"))
            .AsImplementedInterfaces()
            .SingleInstance();

        builder.RegisterType<OrganisationMigrator>().As<IOrganisationMigrator>();
    }
    private static void RegisterShared(ContainerBuilder builder)
    {
        builder.RegisterType<BaseRequestModel>().AsImplementedInterfaces().InstancePerLifetimeScope();
        builder.RegisterType<ImpersonateUser>().As<IImpersonateUser>();
        builder.RegisterModule<NLogModule>();
        builder.RegisterType<ApiApplicationSettings>().As<IApiApplicationSettings>().SingleInstance();
    }

    private static void RegisterPresentationLayer(ContainerBuilder builder, Assembly webApiAssembly)
    {
        builder.RegisterApiControllers(webApiAssembly);
    }

    public static void RegisterHangfireDependency(ContainerBuilder builder)
    {
        RegisterDataLayer(builder);
        RegisterBusinessLayer(builder);
        RegisterShared(builder);
        builder.RegisterType<CronJobManager>().As<ICronJobManager>().InstancePerLifetimeScope();
    }
}
public class NLogModule : Autofac.Module
{
    private static void OnComponentPreparing(object sender, PreparingEventArgs e)
    {
        e.Parameters = e.Parameters.Union(
            new[]
            {
                new ResolvedParameter(
                    (p, i) => p.ParameterType == typeof (ILogger),
                    (p, i) => LogManager.GetLogger(p.Member.DeclaringType.FullName))
            });
    }

    protected override void AttachToComponentRegistration(IComponentRegistry componentRegistry, IComponentRegistration registration)
    {
        // Handle constructor parameters.
        registration.Preparing += OnComponentPreparing;
    }
}

where I try to inject the IServiceScopeFactory

public class PaymentHandler : IPaymentHandler
         {
            private readonly IServiceScopeFactory _serviceScopeFactory;

            public PaymentHandler(IServiceScopeFactory serviceScopeFactory)
            {
        
               _serviceScopeFactory = serviceScopeFactory;

            }
         }

         

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

女皇必胜 2025-01-29 09:07:37

看来您正在尝试进行混合和匹配.NET 4.5依赖项注入(例如,Web API中的dependencyResolver机制)和新的.NET核心依赖性注入(例如,> iserviceProvider)。这里的简短答案是...您不能那样做。

如果您读取例外情况,它将告诉您确切缺少的内容:

无法解析参数'Microsoft.extensions.dependentiondoction.iservicesCopeFactory'

您有一个构造函数,该构造函数采用iServicesCopeFactory。您希望AutoFac注入它。您没有告诉AutoFac 在哪里可以获得它。这里没有魔术:如果您没有向AutoFac注册,则AutoFac将无法弄清楚它。

我想您想要的是在该paymenthandler内创建终身范围的能力。由于与depentencyResolver的Web API中并不是一件事情,因此您必须直接使用AUTOFAC,而不是尝试混合匹配。

而不是注入ilifetimesCope

public class PaymentHandler : IPaymentHandler
{
  private readonly ILifetimeScope _scope;

  public PaymentHandler(ILifetimeScope scope)
  {
    _scope = scope;
    // now you can do
    // using(var childScope = _scope.BeginLifetimeScope){ }
  }
}

此时,,前往autofac Docs 更多地了解终身范围以及如何与他们合作。但这应该使您无障碍。

It appears you're trying to kind of mix-and-match .NET 4.5 dependency injection (e.g., with the DependencyResolver mechanism in Web API) and new .NET Core dependency injection (e.g., IServiceProvider). The really short answer here is... you can't do that.

If you read the exception it tells you exactly what's missing:

Cannot resolve parameter 'Microsoft.Extensions.DependencyInjection.IServiceScopeFactory'

You have a constructor that takes an IServiceScopeFactory. You want Autofac to inject it. You didn't tell Autofac where to get it. No magic here: if you didn't register it with Autofac, Autofac's not going to be able to figure it out.

I'd guess what you want is the ability to create lifetime scopes inside that PaymentHandler. Since that's not really a thing in Web API with DependencyResolver, instead of trying to mix-and-match, you have to use Autofac directly.

Inject the ILifetimeScope instead.

public class PaymentHandler : IPaymentHandler
{
  private readonly ILifetimeScope _scope;

  public PaymentHandler(ILifetimeScope scope)
  {
    _scope = scope;
    // now you can do
    // using(var childScope = _scope.BeginLifetimeScope){ }
  }
}

At this point, it'd be good to head over to the Autofac docs to learn more about lifetime scopes and how to work with them. But this should get you unblocked.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文