简体   繁体   中英

Cannot resolve 'ServiceBusConsumer' from root provider because it requires scoped service DbContext

My application is a asp.net core API.When I am trying to access my db to get information but on running the code it gives me the following exception in my startup class:

'Cannot resolve 'SFOperation_API.Utils.IServiceBusConsumer' from root provider because it requires scoped service '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;
            }
        }
    }

Transient objects are always different; a new instance is provided to every controller and every service.

Scoped objects are the same within a request, but different across different requests.

Singleton objects are the same for every object and every request.

the default life time for DbContext is scoped. Read About DBContext Here You can add Your service as AddScoped.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM