0

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;
            }
        }
    }

1 Answers1

0

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.

Community
  • 1
  • 1
JAvAd
  • 114
  • 1
  • 9
  • I changed my services to -> services.AddSingleton(); services.AddScoped(); services.AddScoped(); Now I get this error -- cannot consume scoped service dbcontext from singleton" – user3682373 Feb 06 '20 at 20:01
  • 1
    Please Test this services.AddScoped(), dont use singleton for any service that relation with db – JAvAd Feb 06 '20 at 20:07
  • @JJorian I made the changes and it worked but now in my repository the context object is disposed and im getting this error --Cannot access a disposed object. A common cause of this error is disposing a context that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur if you are calling Dispose() on the context, or wrapping the context in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context instances. 'DeciemStoreContext'. – Pratik Shukla Feb 06 '20 at 20:13
  • @PratikShukla please change 'protected DeciemStoreContext _context;' to ' private readonly DeciemStoreContext _context;' – JAvAd Apr 24 '21 at 21:34