简体   繁体   English

ASP.NET MVC5控制器和Autofac

[英]ASP.NET MVC5 controller and Autofac

I implemented a design as described here , with ASP.NET MVC5, repository pattern, UoW and Autofac. 我使用ASP.NET MVC5,存储库模式,UoW和Autofac实现了这里描述的设计。

Everything works for controllers with a single service, but I have a controller that requires three services: 一切都适用于具有单一服务的控制器,但我有一个需要三种服务的控制器:

public MyController(IService1 service1, IService2 service2, IService3 service3)
{
    _service1= service1;
    _service2= service2;
    _service3= service3;
}

Now, I register the services like this: 现在,我注册这样的服务:

protected override void Load(ContainerBuilder builder)
{
    builder.RegisterAssemblyTypes(Assembly.Load("namespace.service"))
              .Where(t => t.Name.EndsWith("Service"))
              .AsImplementedInterfaces()
              .InstancePerLifetimeScope();
}

At runtime, I get this error: 在运行时,出现以下错误:

None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' on type 'namespace.Controllers.MyController' can be Invoked with the available services and parameters: Can not resolve parameter '.service.Service1 service1 constructor of 'Void .ctor ... 使用'namespace.Controllers.MyController'类型的'Autofac.Core.Activators.Reflection.DefaultConstructorFinder'找到的构造函数都不能使用可用的服务和参数进行调用:无法解析参数'.service.Service1 service1构造函数'Void .ctor ...

It doesn't really matter how many constructor parameters your controller has. 您的控制器有多少个构造函数参数并不重要。 If Autofac reports that it cannot resolve service1 , it means that IService1 is not registered. 如果Autofac报告无法解析service1 ,则表示IService1未注册。

There might be an issue with registering assembly types due to wrong query or assembly. 由于查询或汇编错误,可能存在注册程序集类型的问题。 To verify this, try commenting out the RegisterAssemblyTypes and use RegisterType<Service1>().As<IService1>().InstancePerRequest() for all three services and see if it helps. 要验证这一点,请尝试注释掉RegisterAssemblyTypes并为所有三个服务使用RegisterType<Service1>().As<IService1>().InstancePerRequest() ,看看是否有帮助。 Also check if your module Load actually gets called. 还要检查模块Load真正被调用。

If registering services explicitly worked, you can try getting back to RegisterAssemblyTypes but use service assembly from the service type instead of loading it by name: 如果注册服务明确有效,您可以尝试返回RegisterAssemblyTypes但使用服务类型的服务程序集,而不是按名称加载它:

    builder.RegisterAssemblyTypes(typeof (Service1).Assembly)
        .Where(t => t.Name.EndsWith("Service"))
        .AsImplementedInterfaces()
        .InstancePerRequest();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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