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] 삭제
몇 마디 만하겠습니다