0

ASP.NET 2를 기반으로하는 MVC 솔루션과 일반 컨트롤러 및 사용자 지정 바인더가 있습니다. 내가 편집 작업을 호출 할 때ASP.NET 코어 - IModelBinder - 액세스 컨트롤러 DbContext

public class GenericController<T> : Controller where T : BaseModel 
{ 
    public readonly AppContext Db = new AppContext(); 

    ... 

    public virtual ActionResult Edit([ModelBinder(typeof(MyCustomBinder))] T obj) 

그래서, 기본적으로 MyCustomBinder 클래스가 호출됩니다

컨트롤러 코드는 다음과 같다. (DefaultModelBinder상속)

MyCustomBinderClass는 무시해야

protected override PropertyDescriptorCollection GetModelProperties(ControllerContext controllerContext, ModelBindingContext bindingContext) 
protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor) 

을 두 가지 방법은 "호출"제어기에 대한 참조를 갖는다. 이제

, 내가 ASP.NET 코어로 전환하고있어 -

dynamic controller = controllerContext.Controller; 
dynamic db = controller.Db; 

:

그래서 나는하여 컨트롤러의 DbContext에 액세스 할 수 있어요. 내가 IModelBinder를 구현해야 사용자 지정 바인더를 생성하기 위해, 그래서 구현해야합니다

public Task BindModelAsync(ModelBindingContext bindingContext) 

질문은, 어떻게 내가 호출 컨트롤러의 DbContext 액세스 할 수 있습니까?

db 데이터 작업을 수행하려면이 작업이 필요합니다.

첫 번째 아이디어는 내 응용 프로그램에 단 하나의 컨텍스트를 갖는 것이 었으며 이는 분명히 잘못되었습니다 (런타임 오류가 발생 함).

하지만 여전히 호출 컨트롤러와 사용자 지정 바인더 모두에서 동일한 컨텍스트가 필요합니다. 그렇지 않으면 엔티티가 2 개의 다른 컨텍스트로 수정된다는 사실 때문에 오류가 발생합니다.

해결 방법에 대한 아이디어가 있습니까?

감사합니다.

답변

0

수동으로 DbContext을 새로 작성하는 대신 종속성 주입에서 해당 인스턴스를 가져 오는 것이 좋습니다.

이렇게하면 생성자 삽입을 통해 DbContext을 쉽게 얻을 수 있습니다.

public class MyCustomBinder : IModelBinder 
{ 
    private readonly AppDbContext _dbContext; 

    public MyCustomBinder(AppDbContext dbContext) 
    { 
     _dbContext = dbContext; 
    } 

    public Task BindModelAsync(ModelBindingContext bindingContext) 
    { 
     ... 
    } 
} 
관련 문제