【发布时间】: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