最近在練.net core 的DI
我在想辦法把Controller 的DBContex挪到service裡
就是這一段
public TransactionController(TransactionDbContext context)
{
_context = context;
}
目前是完成了,但是執行時卻跑出下面這段錯誤
An error occurred while starting the application.
AggregateException: Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: CRUD.DATA.ITransaction Lifetime: Transient ImplementationType: CRUD.Service.TransactionService': Unable to resolve service for type 'CRUD.DATA.ApplicationDbContext' while attempting to activate 'CRUD.Service.TransactionService'.)
這個部份我沒遇過,暫時不知道問題所在
不知道有沒有人能去我的GIT幫我看一下呢?
https://github.com/Jarkwoof/jQuery-Ajax-CRUD
整體架構大概如圖
ApplicationDbContext是放DBContext
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions options) : base(options)
{ }
public List Transactions { get; set; }
}
ITransaction則是定義CRUD相關方法
public interface ITransaction
{
List GetAll();
//TransacrionDto GetById(int id);
//void NewCategory(TransacrionDto category);
//void EditCategory(TransacrionDto category);
//void DeleteCategory(int id);
}
TransactionService則是實作介面裡的方法
public class TransactionService : ITransaction
{
private readonly ApplicationDbContext _context;
public TransactionService(ApplicationDbContext context)
{
_context = context;
}
public List<TransacrionDto> GetAll()
{
var query = (from x in _context.Transactions select new TransacrionDto { }).ToList<TransacrionDto>();
return query;
}
}
Startup.cs
services.AddDbContext<TransactionDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DevConnection")));
泛型改成這樣試試
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DevConnection")));