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,平行世界

  

上一篇:linux查看访问windows共享目录NT_STATUS_DUPLICATE_NAME问题解决


下一篇:使用Visual Studio Code开发Asp.Net Core WebApi学习笔记(六)-- 依赖注入