在ASP.NET核心Web应用程序启动期间,依赖项注入无法注册类

问题描述

program.cs调用CreateHostBuilder.Build()时出现以下异常:

system.invalidOperationException:无法解析类型的服务 尝试激活时“ web_application.Models.postStatus” “ web_application.Services.Updates.PostingStatusUpdater”。

以下是完整错误,但正在Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateArgumentCallSites(Type serviceType,Type ImplementationType,CallSiteChain callSiteChain,ParameterInfo [] parameters,Boolean throwIfCallSiteNotFound)中抛出

搜索了为该依赖项注入dll打开详细日志记录的方法或调试该依赖项注入框架的方法,但找不到相应的答案。如果有人在程序的此阶段知道如何启用详细日志记录,请也免费提供帮助! 这是在Startup.cs中注册服务的方式:

using System;
...

namespace web_application
{
    public class Startup
    {
...

        public void ConfigureServices(IServiceCollection services)
        {   
            services.AddScoped<IUpdateService<postStatus>,PostingStatusUpdater>();

            ...
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app,IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage(); 

            }
            ...
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapRazorPages();
            });
        }
    }
}

postStatus是一个枚举,我首先想到的是DI注册可能由于与之相关的事情而失败。

注册的实际类是从实现通用接口的基类派生的。

通用接口:

using System;
using System.Threading.Tasks;
using System.Collections.Generic;
using web_application.Models;

namespace web_application.Services.Updates{
    public interface IUpdateService<T>{        
        bool runPreUpdateChecks(out IList<string> allFailedChecks);
        void runPostCheckHooks();
        bool tryPerformUpdate(T intialState,T FinalState,Action runUpdate,out IList<string> failureReasons);        
        Task<(bool success,IList<string> updateFailureReasons)> tryPerformUpdateAsync(T intialState,Task runUpdateAsync);        
    }
}

基类:

    using System;
    using System.Threading.Tasks;
    using web_application.Models;
    using System.Collections.Generic;

    namespace web_application.Services.Updates{
        public abstract class BaseStatusUpdater<T> : IUpdateService<T>
        {        
            public T initStatus {get; private set;}
            public T finalStatus {get; private set;}
            // Todo: Add update check attributes
            public List<PreUpdateCheck<T>> preUpdateChecks = new List<PreUpdateCheck<T>>();
            public IList<Action> postUpdateHooks = new List<Action>();

            public BaseStatusUpdater(T initStatus,T finalStatus){
                this.initStatus = initStatus;
                this.finalStatus = finalStatus;
            }
            /// <summary>
            /// Runs preupdate checks and returns every check that Failed (no short circuit)
            /// Returns a list of Failed checks on failure.
            /// </summary>        
            public bool runPreUpdateChecks(out IList<string> allFailedChecks){
                allFailedChecks = new List<string>(preUpdateChecks.Count);
                var allChecksPassed = true;
                foreach(var check in preUpdateChecks){
                    if(!check.run()){
                        allFailedChecks.Add(check.failureReason);
                        allChecksPassed = false;
                    }
                }
                return allChecksPassed;
            }

            /// <summary>
            /// Run only actions that are one-off,and don't cascade into other
            /// actions that may require custom error handling.
            /// </summary>
            public void runPostCheckHooks(){
                foreach(var hook in postUpdateHooks){
                    hook();
                }
            }
            
            public bool tryPerformUpdate(T intialState,out IList<string> updateFailureReasons){
                if(!runPreUpdateChecks(out updateFailureReasons)){
                    return false;
                }
                runUpdate();
                runPostCheckHooks();
                return true;
            }
            
            // https://stackoverflow.com/questions/18716928/how-to-write-an-async-method-with-out-parameter
            public async Task<(bool success,IList<string> updateFailureReasons)> 
            tryPerformUpdateAsync(T intialState,Task runUpdateAsync)
            {
                IList<string> updateFailureReasons = new List<string>(preUpdateChecks.Count);
                if(!runPreUpdateChecks(out updateFailureReasons)){
                    return (false,updateFailureReasons);
                }
                await runUpdateAsync;
                runPostCheckHooks();
                return (true,updateFailureReasons);
            }
        }

    }

正在为IUpdateService注册的类

using System;
using web_application.Models;
using System.Collections.Generic;

namespace web_application.Services.Updates{
    // Make this a singleton on injection to get this so that we don't keep constructing the things
    // in the constructor every time its called? Or store the static logic somewhere else
    using vpStatus = postStatus;
    public class PostingStatusUpdater : BaseStatusUpdater<postStatus>
    {
        public PostingStatusUpdater(vpStatus vpsInitial,vpStatus vpsFinal)
            : base(vpsInitial,vpsFinal)
        {            
            Func<(bool,string)> isMovePermitted = () => { 
                if(UpdateLogic.permittedStatusChanges
                    .Contains(new UpdateLogic.statusPair(base.initStatus,vpsFinal))){
                    return (true,string.Empty);
                }
                return (false,"Cannot mark post as \"" + vpsFinal.ToString() + " since it is currently marked as "
                    + "\"" + vpsInitial.ToString() + "\"");
            };

            var check1 = new PreUpdateCheck<vpStatus>(isMovePermitted);
            base.preUpdateChecks.Add(check1);
        }


    }

}

没有关于此的编译时错误或警告,我一直在研究以确保以前未解决此问题,但是我找不到确切解决此问题的问题,因此我想将其发布以寻求帮助。

谢谢。


完整错误

引发的异常:“ System.AggregateException” Microsoft.Extensions.DependencyInjection.dll:“某些服务不是 能够被构造”发现内部异常,有关更多详细信息,请参见变量窗口中的$ exception。 最内在的例外 system.invalidOperationException:无法解析类型的服务 尝试激活时“ web_application.Models.postStatus” “ web_application.Services.Updates.PostingStatusUpdater”。 在 Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateArgumentCallSites(Type serviceType,Type ImplementationType,CallSiteChain,callSiteChain, ParameterInfo []参数,布尔值throwIfCallSiteNotFound)位于 Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateConstructorCallSite(ResultCache 生命周期,类型serviceType,类型ImplementationType,CallSiteChain callSiteChain) Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateExact(ServiceDescriptor 描述符,类型serviceType,CallSiteChain,callSiteChain,Int32插槽) 在 Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.GetCallSite(ServiceDescriptor serviceDescriptor,CallSiteChain callSiteChain) Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.ValidateService(ServiceDescriptor 描述符)

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...