In this post I discussed creating a custom Model Binder. The next question I had was, “how can I access my database in that binder?” Before you spend hours beating your head against the wall, let me just say that it’s pretty easy.
I’m going to assume that you have something like this in your program.cs file:
builder.Services.AddDbContext<DataContext> (options => options.UseMySQL (builder.Configuration.GetConnectionString ("MySqlConnection")!));
This creates a Data Context which you can use to access your database. Your controller class may have something like this as a class parameter:
class SomeControllerClass (DataContext context) {
...
}// SomeControllerClass;
And then, in your API method you may have something that accesses that data context using, say, a linq (yes, that is a complete sentence – “linq” stands for “Language-Integrated Query”, so a “linq query” would be a “Language-Integrated Query query”, which is a tautology):
List<SomeType> result = (from tbl in context.table select tbl).ToList ();
The method has access to the data context because of Dependency Injection. For those old school programmers like myself (who use the term “programmer” instead of “developer”), don’t freak out. Dependency Injection (or DI) is not some new voodoo. It’s merely a buzz-term for “passing a parameter to a method”. Whenever you see “Dependency Injection” or DI, you can substitute the concept, pass a parameter.
Anyway, it works the same way. We’re passing (or rather, the .Net framework) is passing a parameter to the class. We can define our binding class like so:
public class CustomBinder (DataContext data_context): IModelBinder {
...
}// CustomBinder;
And, bingo, we have access to the data context. Note that we’re declaring the parameter on the class. This is a new feature of .Net, and it’s pretty cool. We could just as easily have done this:
public class CustomBinder: IModelBinder {
private DataContext context;
public CustomBinder (DataContext context) {
this.context = context
}// Constructor;
}// CustomBinder;
That would have exactly the same effect, but the new syntax allows us to dispense with declaring the private variable and constructor.
Leave a Reply