Skip to content

Hosting: Custom Model Binding not used, not found in service collection  #1468

Open
@BobSilent

Description

@BobSilent

I am using the commandline hosting and added
a custom model binder like shown here

.AddMiddleware(context =>
{
var binder = new ModelBinder<ClassWithSetter<int>>();
binder.BindMemberFromValue(instance => instance.Value, _ => 456);
context.BindingContext.AddModelBinder(binder);
})

but the model binder is not used, as the logic tries to find the binder in the service collection, but it was not added before:

var modelBinder = serviceProvider
.GetService<ModelBinder<TOptions>>()
?? new ModelBinder<TOptions>();
var bindingContext = serviceProvider.GetRequiredService<BindingContext>();
modelBinder.UpdateInstance(opts, bindingContext);

when manually adding the model binder to service collection it gets used.

Is this the expected behavior to manually add the model binder to service collection or should it be enough when adding the model binder to the BindingContext?

P.S. in a non dependency injection context the custom model binder works as expected.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions