繁体   English   中英

Autofac asp.net MVC控制器和ViewModel

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM