c# - Autofac 与 Web Api 集成时出错

标签 c# asp.net-web-api autofac

我们的应用程序分为以下五个项目:

  • 只有 Html 页面的项目
  • Web Api 项目,充当服务层,仅包含 ApiController 类
  • 业务层类库
  • 仅包含接口(interface)的业务层契约类库
  • 数据层类库
  • 数据层契约类库,也仅包含接口(interface)

Web Api 服务包含对所有类库以及 Autofac 和 AutofacWebApiDependencyResolver 的引用。

我已经添加了注册容器和解析器所需的代码,如 Autofac 文档中所述:

    var builder = new ContainerBuilder();
    builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

    var container = builder.Build();
    var resolver = new AutofacWebApiDependencyResolver(container);
    GlobalConfiguration.Configuration.DependencyResolver = resolver;

目前我有一个非常基本的依赖层次结构来测试它,如下所示:

//On the data contracts
public interface IData
{
   void SomeDataMethod();
}

//On the data layer
public class Data : IData
{
   public void SomeDataMethod(){}
}

//On the business contracts
public interface IBusiness
{
   void SomeBusinessMethod();
}

//On the business layer
public class Business : IBusiness
{
   private readonly IData _data;

   public Business(IData data)
   {
      _data = data;
   }
}

//On the Web Api project
[EnableCors("*", "*", "*")]
public class MyController : ApiController
{
   private IBusiness _business;

   public MyController(IBusiness business)
   {
      _business = business;
   }
}

所以这里根本没有火箭科学,但是当我运行该项目时,我收到以下错误:

 XMLHttpRequest cannot load http://localhost:61101/api/MyController. No
 'Access-Control-Allow-Origin' header is present on the requested
 resource. Origin 'http://localhost:56722' is therefore not allowed
 access.

如果我从 Controller 中删除构造函数,应用程序将完美运行, Controller 将被实例化并调用其 get 方法。

我可能做错了什么?

最佳答案

显然,令人困惑的错误会让您相信这确实是未启用 CORS 的问题,原因是向 Autofac Web Api 集成程序集注册 Controller 的代码不够,您还需要手动注册所有其他程序集中的所有依赖项。

因此 Global.asax 文件中的代码最终如下所示:

    var builder = new ContainerBuilder();
    builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

    var assemblies = AppDomain.CurrentDomain.GetAssemblies().ToList();
    var appAssemblies = assemblies.Where(a => a.ToString().StartsWith("MyCustomer.MyApplicationName") && !a.ToString().Contains("Services")).ToArray();
    builder.RegisterAssemblyTypes(appAssemblies).AsImplementedInterfaces();

    var container = builder.Build();
    var resolver = new AutofacWebApiDependencyResolver(container);
    GlobalConfiguration.Configuration.DependencyResolver = resolver;

这是有效的,因为我的每个程序集都是按照约定命名的:

CustomerName.ApplicationName.LayerName

因此,我希望应用程序程序集的所有类型(服务程序集除外)都注册到 Autofac。

关于c# - Autofac 与 Web Api 集成时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24024737/

相关文章:

c# - 从 XML 文档创建的 Json 反序列化到 POCO 不适用于数组

c# - WPF app.run 不工作?

c# - 如何更改文件名以保存在特定文件夹中

c# - 不使用 Autofac 命名空间的隐式解析范围

.net - 解析实例 - Autofac

C# 类型 _ 没有定义构造函数

c# - 为什么对象没有接受 IFormatProvider 的重载?

web-services - WebAPI 的开源等价物是什么?

c# - Power Query/PowerBI连接到通过AAD保护的自定义oDATA提要

asp.net-mvc - ServiceStack MemoryCacheClient 不缓存