简体   繁体   English

Autofac - 依赖注入MVC​​控制器和Web Api控制器

[英]Autofac - dependency injection for MVC controller and Web Api controller

I have MVC controllers (in Controllers folder) and Web Api controllers (in Api folder) in the same project: Here is the folder structure: 我在同一个项目中有MVC控制器(在Controllers文件夹中)和Web Api控制器(在Api文件夹中):这是文件夹结构:

  • Controllers 控制器
    • ProductController ProductController的
  • Api API
    • ProductController ProductController的

Here is my bootstrapper method: 这是我的bootstrapper方法:

        private static void SetAutofacContainer()
        {
            var builder = new ContainerBuilder();
            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
            builder.RegisterControllers(Assembly.GetExecutingAssembly());
            //builder.RegisterType<UnitOfWork>().As<IUnitOfWork>().InstancePerRequest();
            builder.RegisterType<DbFactory>().As<IDbFactory>().InstancePerRequest();

            // Repositories
            builder.RegisterAssemblyTypes(typeof(ProductRepository).Assembly)
                .Where(t => t.Name.EndsWith("Repository"))
                .AsImplementedInterfaces().InstancePerRequest();

            IContainer container = builder.Build();
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        }

I can not inject repositories to my Web Api controllers. 我无法将存储库注入我的Web Api控制器。 Here is the exception I get: 这是我得到的例外:

An error occurred when trying to create a controller of type 'ProductController'. 尝试创建“ProductController”类型的控制器时发生错误。 Make sure that the controller has a parameterless public constructor. 确保控制器具有无参数的公共构造函数。

What am I doing wrong? 我究竟做错了什么?

You haven't set Web API's GlobalConfiguration.Configuration.DependencyResolver ; 您尚未设置Web API的GlobalConfiguration.Configuration.DependencyResolver ; you only set MVC's DependencyResolver . 你只设置了MVC的DependencyResolver

Add the following line: 添加以下行:

GlobalConfiguration.Configuration.DependencyResolver =
    new AutofacWebApiDependencyResolver(container);

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

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