I was in exactly same situation. I needed to instantiate object from database and then let MVC/Core bind all the properties for me. After hours of googling and "stackoverflowing" this is what I built:
public class MyBinder : ComplexTypeModelBinder
{
public MyBinder(IDictionary<ModelMetadata, IModelBinder> propertyBinders) : base(propertyBinders, new LoggerFactory()) { }
protected override object CreateModel(ModelBindingContext bindingContext)
{
return Get_Object_From_Database(); //custom creation logic
}
}
public class MyBinderProvider : IModelBinderProvider
{
public IModelBinder GetBinder(ModelBinderProviderContext context)
{
//make sure I use it with my type only
if (context.Metadata.ModelType == typeof(My_Object))
{
//get property binders for all the stuff
var propertyBinders = context.Metadata.Properties.ToDictionary(p => p, p => context.CreateBinder(p));
return new MyBinder(propertyBinders);
}
return null;
}
}
//startup.cs
services.AddMvc(option =>
{
option.ModelBinderProviders.Insert(0, new MyBinderProvider());
});
ComplexTypeModelBinder
is marked obsolete, but MS team has said on github that this means the type should not be used internally by MS, but it will stay.
Tested successfully with .NET 5