0

I have an MVC solution based on ASP.NET 2, with a generic controller and a custom binder.

The controller code is the following:

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

    ...

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

So, basically, when I call the Edit action the MyCustomBinder class is called.

The MyCustomBinderClass (which inherits from DefaultModelBinder) need to override:

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

and both methods have a reference to the "calling" controller.

So I'm able to access the controller's DbContext by:

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

--

Now, I'm switching to ASP.NET core. In order to create a custom binder I need to implement IModelBinder, so I need to implement:

public Task BindModelAsync(ModelBindingContext bindingContext)

The question is, how can I access the DbContext of the calling controller?

I need that in order to perform operations on db data.

First idea was to have only one context in my application, which is obviously wrong (and leads to runtime errors).

But I still need to have the same context both in the calling controller and in the custom binder; otherwise this also leads to errors due to the fact that entities are modified in 2 different contexts.

Any idea on how to solve that?

Thanks!

Guido Lo Spacy
  • 429
  • 1
  • 4
  • 20

1 Answers1

0

I would recommend, instead of newing the DbContext manually, to get its instance from the Dependency injection.

With that said, you can easily get the DbContext through constructor injection.

public class MyCustomBinder : IModelBinder
{
    private readonly AppDbContext _dbContext;

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

    public Task BindModelAsync(ModelBindingContext bindingContext)
    {
        ...
    }
}
David Liang
  • 20,385
  • 6
  • 44
  • 70