[英]Autofac asp.net MVC controller and viewmodel
我收到此錯誤:[MissingMethodException:沒有為此對象定義無參數構造函數。 對象類型'MyProject.TestViewModel'。]
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)'.
我想堅持使用構造函數注入,但是我不知道我在這里缺少什么。
您具有TestSvc1
的依賴TestSvc1
,但沒有任何服務被注冊為該類型。 您已將TestSvc1
注冊為ITestSvc
,僅此而已。 如果要改為注入TestSvc1
,則需要將AsSelf()
添加到其注冊中。
builder.RegisterType<TestSvc1>()
.As<ITestSvc>()
.AsSelf();
或更改您的視圖模型,使其接受ITestSvc
。 這可能是首選的解決方案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.