簡體   English   中英

Autofac與Web Api集成時出錯

[英]Error with Autofac integration with Web Api

我們有一個分為五個項目的應用程序,這些項目如下:

  • 只有HTML頁面的項目
  • Web Api項目,用作僅包含ApiController類的服務層
  • 業務層類庫
  • 業務層合同類庫,僅包含接口
  • 數據層類庫
  • 數據層合同類庫,其中僅包含接口

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.

如果我從控制器中刪除構造函數,則應用程序將正常運行,控制器將實例化,並調用其get方法。

我可能做錯了什么?

顯然,令人困惑的錯誤會導致您認為未啟用CORS確實是一個問題,是由於以下事實造成的:在Autofac Web Api集成程序集中注冊控制器的代碼不足,您還需要注冊手動所有其他程序集中的所有依賴項。

因此,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。

看起來像是CORS問題。 就像在Web API WebApiConfig.Register()函數中未啟用CORS一樣簡單嗎? 例如,您將添加:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.EnableCors();

        // etc.
    }
}

將其與控制器的EnableCors屬性結合使用。

另外,您可以像下面這樣在全局范圍內啟用CORS(而不只是控制器):

var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);

請注意,通常最好限制您的CORS規則,而不是在所有位置都使用"*"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM