【问题标题】:Cannot resolve 'ServiceBusConsumer' from root provider because it requires scoped service DbContext无法从根提供程序解析“ServiceBusConsumer”,因为它需要范围服务 DbContext
【发布时间】:2020-05-22 22:28:45
【问题描述】:

我的应用程序是一个 asp.net 核心 API。当我试图访问我的数据库以获取信息但在运行代码时它在我的启动类中给了我以下异常:

'无法从根目录解析'SFOperation_API.Utils.IServiceBusConsumer' 提供者,因为它需要范围服务 'SFOperation_API.Domain.Persistence.Contexts.DeciemStoreContext'

Startup.cs

public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;


        }

        public IConfiguration Configuration { get; }

        public static string clientId
        {
            get;
            private set;
        }

        public static string clientSecret
        {
            get;
            private set;
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            string azureConnectionString = Configuration["ConnectionStrings:DefaultConnection"];

            services.AddControllers();
            clientId = Configuration.GetSection("fuelSDK").GetSection("clientId").Value;
            clientSecret = Configuration.GetSection("fuelSDK").GetSection("clientSecret").Value;

            var dbUtils = new AzureDatabaseUtils();
            var sqlConnection = dbUtils.GetSqlConnection(azureConnectionString);

            services.AddDbContext<DeciemStoreContext>(options =>
                options.UseSqlServer(sqlConnection));

            #region RegisterServices

            services.AddTransient<IServiceBusConsumer, ServiceBusConsumer>();
            services.AddTransient<IOrderRepository, OrderRepository>();
            services.AddTransient<IOrderService, OrderService>();

            #endregion






            Configuration.GetSection("Global").Get<Global>();
        }

        // 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();
            }

            #region Azure ServiceBus


            #endregion

//I am getting the exception on the below line
            var bus = app.ApplicationServices.GetService<IServiceBusConsumer>();
            bus.RegisterOnMessageHandlerAndReceiveMessages();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute("api", "api/{controller}/{action}/{id?}");
            });
        }
    }

OrderRepository.cs

public class OrderRepository :  IOrderRepository
    {
        protected DeciemStoreContext _context;
        public OrderRepository(DeciemStoreContext context) 
        {
            _context = context;
        }

        public async Task<IEnumerable<Order>> ListAsync()
        {

            return await _context.Order.ToListAsync();
        }

        public async Task<List<Order>> GetByOrderId(string OrderId)
        {
            try
            {
                int oid = Convert.ToInt32(OrderId);

                //receiving error here as Context disposed
                var order = from o in _context.Order
                            where o.OrderId == oid
                            orderby o.OrderId
                            select new Order
                            {
                                OrderId = o.OrderId,
                                CustomerId = o.CustomerId,
                                ProductSubtotal = o.ProductSubtotal,
                                PreTaxSubtotal = o.PreTaxSubtotal,
                                DiscountCode = o.DiscountCode,
                                DiscountPercent = o.DiscountPercent,
                                DiscountAmount = o.DiscountAmount,
                                GrandTotal = o.GrandTotal,
                                Ponumber = o.Ponumber,
                                PostedDate = o.PostedDate
                            };

                return await order.ToListAsync();
            }
            catch(Exception ex) {
                throw ex;
            }
        }
    }

【问题讨论】:

    标签: c# dependency-injection asp.net-core-2.1 webapi


    【解决方案1】:

    瞬态对象总是不同的;为每个控制器和每个服务提供一个新实例。

    作用域对象在一个请求中是相同的,但在不同的请求中是不同的。

    单个对象对于每个对象和每个请求都是相同的。

    DbContext 的默认生命周期是有范围的。 Read About DBContext Here 您可以将您的服务添加为 AddScoped。

    【讨论】:

    • 我将服务更改为 -> services.AddSingleton(); services.AddScoped(); services.AddScoped();现在我收到此错误 - 无法从单例中使用作用域服务 dbcontext"
    • 请测试此 services.AddScoped(),不要对任何与 db 相关的服务使用单例
    • @JJorian 我进行了更改并且它工作但现在在我的存储库中,上下文对象已被释放,我收到此错误 - 无法访问已释放的对象。此错误的一个常见原因是释放从依赖注入中解析的上下文,然后尝试在应用程序的其他地方使用相同的上下文实例。如果您在上下文上调用 Dispose() 或将上下文包装在 using 语句中,则可能会发生这种情况。如果你使用依赖注入,你应该让依赖注入容器负责处理上下文实例。 'DeciemStoreContext'。
    • @PratikShukla 请更改“受保护的 DeciemStoreContext _context;” to '私有只读 DeciemStoreContext _context;'
    猜你喜欢
    • 1970-01-01
    • 2022-10-18
    • 2020-08-01
    • 2021-10-11
    • 2018-04-04
    • 1970-01-01
    • 2020-09-06
    • 2020-05-11
    • 1970-01-01
    相关资源
    最近更新 更多