[英]Autofac asp.net MVC controller and viewmodel
I'm getting this error: [MissingMethodException: No parameterless constructor defined for this object. 我收到此错误:[MissingMethodException:没有为此对象定义无参数构造函数。 Object type 'MyProject.TestViewModel'.] 对象类型'MyProject.TestViewModel'。]
Global.asax.cs 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));
Controller 控制者
public class MyAccountController : BaseController
{
public ActionResult Test(TestViewModel testViewModel)
{
_testViewModel = testViewModel;
return View(_testViewModel);
}
ViewModel 视图模型
public class TestViewModel : ITestViewModel
{
private TestSvc1 _testSvc1;
public string ViewModelText { get; set; }
public TestViewModel(TestSvc1 testSvc1)
{
_testSvc1 = testSvc1;
ViewModelText = _testSvc1.GetText();
}
}
Are there additional steps I need to take with this? 我需要采取其他步骤吗? I was expecting that once I had registered the builder.RegisterType().As(); 我期望一旦注册了builder.RegisterType()。As(); I would be good to go. 我会去的。 I have tried to do the injection at the controller level in that constructor, and it gives me 我试图在该构造函数中的控制器级别进行注入,这给了我
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)'.
I'd like to stick with constructor injection, I don't know what I'm missing here. 我想坚持使用构造函数注入,但是我不知道我在这里缺少什么。
You have a dependency on TestSvc1
, but no service is registered as that type. 您具有TestSvc1
的依赖TestSvc1
,但没有任何服务被注册为该类型。 You have TestSvc1
registered as a ITestSvc
, and only as that. 您已将TestSvc1
注册为ITestSvc
,仅此而已。 If you want to instead inject TestSvc1
, you will need to add AsSelf()
to its registration. 如果要改为注入TestSvc1
,则需要将AsSelf()
添加到其注册中。
builder.RegisterType<TestSvc1>()
.As<ITestSvc>()
.AsSelf();
Or change your viewmodel so it accepts a ITestSvc
. 或更改您的视图模型,使其接受ITestSvc
。 This is probably the preferred solution. 这可能是首选的解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.