Autofac asp.net MVC控制器和viewmodel

时间:2016-11-01 14:22:35

标签: c# asp.net-mvc autofac

我收到此错误: [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)'.

我想坚持使用构造函数注入,我不知道我在这里失踪了什么。

1 个答案:

答案 0 :(得分:0)

您依赖TestSvc1,但没有注册任何服务作为该类型。您已将TestSvc1注册为ITestSvc,并且只能注册为TestSvc1。如果您想要注入AsSelf(),则需要在注册时添加builder.RegisterType<TestSvc1>() .As<ITestSvc>() .AsSelf();

ITestSvc

更改您的viewmodel,使其接受var people= toBeSorted.select (p => new {Name = p[0], LastName = p[1], City = p[2]}); var sorted = people.OrderBy(p => p.LastName); 。这可能是首选的解决方案。