単純なgetCustomers()
メソッドを持つAPIをセットアップしました。エンドポイントは最初の呼び出しでデータを返しますが、2回目の呼び出しではエラーを返します。複数のコールで 'DbContextが処理されませんでした'
Error: The operation cannot be completed because the DbContext has been disposed
エラーが上で私のCustomerService
内引き起こされreturn db.Customers...
Question: Why does this work on the first call, but fail on the second call. How can this be resolved?
GitHubのレポは、ここで見つけることができます:
:ここ https://github.com/ChaseHardin/MyBookStoreは、コードのウォークスルーです
コントローラ:
[RoutePrefix("api/customers")]
public class CustomerController : ApiController
{
private readonly CustomerService _service = new CustomerService();
[HttpGet, Route("")]
public virtual IHttpActionResult Get()
{
var customers = _service.GetCustomers();
return Ok(new {customers});
}
}
カスタマーサービス:
public class CustomerService : BaseService
{
public List<CustomerViewModel> GetCustomers()
{
using (var db = Application.GetDatabaseInstance())
{
return db.Customers.Select(AutoMapper.Mapper.Map<CustomerViewModel>).ToList();
}
}
}
BaseService
public class BaseService
{
public BaseService()
{
AutoMapperConfiguration();
}
public void AutoMapperConfiguration()
{
Assembly.GetExecutingAssembly()
.GetTypes()
.Where(x => x.IsClass && x.Namespace == "MyBookStore.Business.ViewModels")
.ForEach(x => System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(x.TypeHandle));
AutoMapper.Mapper.CreateMap<bool, short?>().ConvertUsing(x => x ? (short)1 : (short)0);
AutoMapper.Mapper.CreateMap<short, bool>().ConvertUsing(x => x == 1);
AutoMapper.Mapper.CreateMap<bool, int?>().ConvertUsing(x => x ? 1 : 0);
AutoMapper.Mapper.CreateMap<int?, bool>().ConvertUsing(x => x.HasValue && x.Value == 1);
AutoMapper.Mapper.CreateMap<short, int>().ConvertUsing(x => (int)x);
AutoMapper.Mapper.CreateMap<int, int?>().ConvertUsing(x => x);
}
}
CustomerViewModel
public class CustomerViewModel
{
static CustomerViewModel()
{
AutoMapper.Mapper.CreateMap<Customer, CustomerViewModel>().ReverseMap();
}
public Guid CustomerId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
コンテキストセットアップ:
public class Application
{
private static readonly MyBookStoreEntity Context = new MyBookStoreEntity();
public static MyBookStoreEntity GetDatabaseInstance()
{
return Context;
}
}
コンテキストがシングルトンで、使用後に処分しているようです。 –
あなたはusingステートメント内で静的コンテキストを使用していますので、一度使用すれば処分されます。静的コンテキストを使用しないでください! – DavidG
静的なデータベースコンテキストは、有名な*悪い考えです。理由の1つを発見しました。 – David