asp.net startup.cs类中注入的接口为空

stszievb  于 2023-06-07  发布在  .NET
关注(0)|答案(1)|浏览(169)

net core exception handling in asp.net core 5 project but I want to保存the exception in sql server database,but unfortunately when I inject that class have the insert method of exception to database it throw null reference exception for injected interface into startup class:

private readonly IExceptionService exceptionService;
        public Startup(IExceptionService exceptionService)
        {
            this.exceptionService = exceptionService;
        }
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        { app.UseExceptionHandler(a => a.Run(async context =>
            {
                var exceptionHandlerPathFeature = context.Features.Get<IExceptionHandlerPathFeature>();
                var exception = exceptionHandlerPathFeature.Error;

                //  For Save Exception Log
                if (exceptionService is not null)
                {
                    exceptionService.AddException(exception);
                }
                // For Show Json Error in Resoponse
                await context.Response.WriteAsJsonAsync(new DTOResultObject(exception.Message));
            })); 
}

我的启动类在第一个有另一个构造函数:

public IConfiguration Configuration { get; }

        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;

        }

能帮我解决这个问题吗?谢谢,空引用Exception Error正好是这一行的exceptionService:

if (exceptionService is not null)
                {
                    exceptionService.AddException(exception);
                }
vuktfyat

vuktfyat1#

你应该像下面这样在ConfigureServices方法中注册它。

// This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        ...

        services.AddSingleton<IExceptionService, Your_SQLExceptionService>();
        ...
    }

我也做了一些研究,找到一个有用的回购给你。它像下面这样注册ExceptionService

services.AddSingleton<IExceptionService, ExceptionService>();

您可以参考此内容来实现Your_SQLExceptionService,如下所示

using System.Threading.Tasks;

namespace MVCPro.ActionFilters
{
    public interface IExceptionService
    {
        void Save(Exception ex);
    }

    public class ExceptionService : IExceptionService
    {
        private readonly IServiceProvider _serviceProvider;
        public ExceptionService(IServiceProvider serviceProvider)
        {
            _serviceProvider = serviceProvider;
        }
        public void Save(Exception ex)
        {
            using (var scope = _serviceProvider.CreateScope())
            {
                var _context = scope.ServiceProvider.GetRequiredService<MVCProContext>();
                _context.Add(new Book() { Title = ex.Message });
                _context.SaveChanges();
            }
        }
    }
}

相关问题