2016-11-01 2 views
0

이 오류 : [MissingMethodException :이 개체에 대해 정의 된 매개 변수가없는 생성자가 없습니다. 개체 유형 'MyProject.TestViewModel'.]Autofac MVC 컨트롤러 및 viewmodel

Global.asax.cs

var builder = new ContainerBuilder(); 
builder.RegisterControllers(typeof(MvcApplication).Assembly); 
builder.RegisterType<MyProfileStore>().As<IMyProfileStore>(); 
builder.RegisterType<BreadCrumbImageService>().As<IBreadCrumbImageService>().SingleInstance(); 
builder.RegisterType<MyProfileViewModel>().As<IMyProfileViewModel>(); 
builder.RegisterType<BaseViewModel>().As<IBaseViewModel>(); 
builder.RegisterType<TestViewModel>().As<ITestViewModel>(); 
builder.RegisterType<TestSvc1>().As<ITestSvc>(); 
builder.RegisterType<TestSvc3>().As<ITestSvc>(); 
builder.RegisterType<TestSvc2>().As<ITestSvc>(); 
var container = builder.Build(); 
DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); 

컨트롤러

public class MyAccountController : BaseController 
{ 
    public ActionResult Test(TestViewModel testViewModel) 
    { 
     _testViewModel = testViewModel; 
     return View(_testViewModel); 
    } 

뷰 모델

public class TestViewModel : ITestViewModel 
{ 
    private TestSvc1 _testSvc1; 
    public string ViewModelText { get; set; } 

    public TestViewModel(TestSvc1 testSvc1) 
    { 
     _testSvc1 = testSvc1; 
     ViewModelText = _testSvc1.GetText(); 
    } 
} 

내가 함께 수행해야하는 추가 단계가 있습니까 이? builder.RegisterType(). As();를 등록했으면 기대하고있었습니다. 나는 갈 것이 좋다. 그 생성자 컨트롤러 수준에서 주입을 위해 노력했다, 그리고 내가, 내가 여기에 누락 모르는 생성자 주입을 고수하고 싶습니다 나에게

None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' on type 'MyProject.MyAccountController' can be invoked with the available services and parameters: 
Cannot resolve parameter 'MyProject.TestViewModel testViewModel' of constructor 'Void .ctor(MyProject.TestViewModel)'. 

을 제공합니다.

+0

이 질문에 대한 답변 : http://stackoverflow.com/a/40362993/8116 –

답변

0

TestSvc1에 종속되어 있지만 해당 유형으로 등록 된 서비스가 없습니다.은 ITestSvc으로 등록되어 있습니다. 대신 TestSvc1을 삽입하려면 AsSelf()을 등록에 추가해야합니다.

builder.RegisterType<TestSvc1>() 
    .As<ITestSvc>() 
    .AsSelf(); 

아니면이 ITestSvc을 받아 귀하의 ViewModel을 변경. 이것은 아마도 선호되는 해결책 일 것입니다.

+0

Amy에게 답장을 보내 주셔서 감사합니다! 나는 그것을 AsSelf()로 바꿨고, 여전히 괴팍하지만 두번째 오류 메시지가 나온다. ITestSvc를 속성 및 뷰 모델 생성자에 넣으려고했지만 차이점이 없습니다. 다른 생각? 나는 여기서 뭔가 근본적인 것을 놓치고있는 것처럼 느껴진다. 그러나 이것은 내 프로젝트 중 하나에서 Autofac을 설정하는 나의 처음이다. 감사! 편집 : 원래의 오류 메시지로 돌아가서, 어떤 것이 제대로 다시 빌드되지 않았거나 bin 폴더에 도착하지 않았습니다. – plankalkul

+0

아마도 'TestViewModel'등록에 동일하게 적용됩니다. 'Foo'를 삽입하려면'Foo'로 등록해야합니다. 'IFoo '로 등록되어 있다면'Foo'로 삽입 할 수 없습니다. Autofac은 제공 방법을 모릅니다. 등록을 하나씩 살펴보고 클래스가 구체적인 클래스가 아니라 등록 된 서비스에 대한 종속성을 두 번 확인하십시오. – Amy

+0

나는 이와 같이 주입 된 뷰 모델을 본 적이 없다고 덧붙이고 싶습니다. 네가하려는 일이 가능하거나 나쁜 습관인지는 모르겠다. 나쁘다는 말은하지 않는다. 일반적으로 모델이 아닌 서비스를 주입합니다. – Amy