ASP.NET Core修改IOC為Autofac


   如下是我為了了解如何更換ASP.NET Core中的IOC而查找的文章,如果大家英文OK的,可以直接前往閱讀,同時也已經有簡單的github例子供大家參考。

參考文章:

ASP.NET Core文檔:https://docs.asp.net/en/latest/fundamentals/dependency-injection.html#replacing-the-default-services-container

Autofac文檔:http://docs.autofac.org/en/latest/integration/aspnetcore.html

Autofac官網的Example:https://github.com/autofac/Examples/tree/master/src/AspNetCoreExample

有了上面的參考文章,其他多余的廢話也不說了,直接說重點。

1. 在Nuget上,找到Autofac和Autofac.Extensions.DependencyInjection,直接安裝。

2. 修改Startup.cs中的代碼,主要ConfigureServices(IServiceCollection services)方法。其中該方法默認的返回值為void,這里需要修改返回值為IServiceProvider。代碼如下:

public IContainer ApplicationContainer { get; private set; }

// ConfigureServices is where you register dependencies. This gets
  // called by the runtime before the Configure method, below.
  public IServiceProvider ConfigureServices(IServiceCollection services)
  {
    // Add services to the collection.
    services.AddMvc();

    // Create the container builder.
    var builder = new ContainerBuilder();

    // Register dependencies, populate the services from
    // the collection, and build the container. If you want
    // to dispose of the container at the end of the app,
    // be sure to keep a reference to it as a property or field.
    builder.RegisterType<MyType>().As<IMyType>();
    builder.Populate(services);
    this.ApplicationContainer = builder.Build();

    // Create the IServiceProvider based on the container.
    return new AutofacServiceProvider(this.ApplicationContainer);
  }

 

 推薦一下自己的網站:www.mylofter.com:81,平行世界

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM