使用Visual Studio 2017我有一个ASP.NET Core MVC 应用程序。我注册了我工厂的必要方法,因为在模型中每个我的类的每个实例只能通过工厂创建:
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<ITechnicalTask>(_ =>
// It returns ITechnicalTask instance
ModelFactory.Current.CreateTechnicalTaskTemplate(
"Template Name"));
// Add framework services.
services.AddMvc();
}
我的控制器有这样的方法:
[HttpGet]
public IActionResult CreateTemplate() => View();
[HttpPost]
public IActionResult CreateTemplate(ITechnicalTask item)
{
repo.Templates.Add(item);
return View("TemplatesList");
}
这是我的表格:
<form asp-action="CreateTemplate" method="post">
<div class="form-group">
<label asp-for="TemplateName">Template name:</label>
<input class="form-control" asp-for="TemplateName" />
</div>
<div class="text-center">
<button class="btn btn-primary" type="submit">
Accept
</button>
</div>
</form>
当我按下Accept
按钮时出现异常:
处理请求时发生未处理的异常。
InvalidOperationException: 无法创建类型为“PikProject.RobotIRA.ITechnicalTask”的实例。模型绑定复杂类型不能是抽象类型或值类型,并且必须具有无参数构造函数。
Microsoft.AspNetCore.Mvc.ModelBinding.Binders.ComplexTypeModelBinder.CreateModel(ModelBindingContext bindingContext)
为什么它需要默认构造函数?为什么用我的工厂方法还不够?
UPD
我的商业模式位于其他项目中。它的所有类都是internal
. 只有接口和耦合类是public
. 它还定义了用于创建接口的必要实例的工厂接口:
public interface IModelFactory {
IEmployee CreateEmployee(string name,
string middleName, string surname,
string post);
IAddress CreateAddress(string country, string region,
string town, string street, string hoseNumber = "",
string notes = "");
IApproval CreateApproval(IEmployee employee,
DateTime? datetime = null);
IApprovalCollection CreateApprovalCollection();
IRequirementsCollection CreateRequirementsCollection();
IRequirement CreateRequirement(RequirementTypes type);
ITechnicalTask CreateTechnicalTaskTemplate(string name);
ITechnicalTask CreateTechnicalTaskDocument(
string templateName);
ITechnicalTaskCollection CreateTechnicalTaskCollection();
IRepository CreateRepository();
}
当前工厂始终可以通过该ModelFactory.Current
程序集的属性访问。因此,在我的ASP.NET Core MVC
项目中没有可访问的类或构造函数。
你混淆了依赖注入和模型绑定。有一个很大的不同。请考虑执行以下操作。
注册IModelFactory
为服务:
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IModelFactory>(ModelFactory.Current);
// Add framework services.
services.AddMvc();
}
现在在您的控制器中,使用FromServices
获取实例并从帖子中获取使用创建模型所需的值FromForm
:
[HttpPost]
public IActionResult CreateTemplate([FromForm] string name,
[FromServices] IModelFactory factory)
{
var item = factory.CreateTechnicalTaskTemplate(name);
repo.Templates.Add(item);
return View(nameof(TemplatesList));
}
你的工厂应该被视为一种服务。模型绑定需要 POCO,而不是接口。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句