前面的博客主要介绍了一些Autofac
的使用方法,示例代码都是基于控制台程序。本文就来介绍一下如何在ASP.NET Core
中使用Autofac
代替内置的IoC
容器。
这里搭建了一个简易的项目,如下图所示:
namespace App.Service.Contract
{
public interface ICatService
{
string Get();
}
}
namespace App.Service.Contract
{
public interface IDogService
{
string Get();
}
}
using App.Service.Contract;
namespace App.Service
{
public class CatService : ICatService
{
public string Get()
{
return "This is cat";
}
}
}
using App.Service.Contract;
namespace App.Service
{
public class DogService : IDogService
{
public string Get()
{
return "This is dog";
}
}
}
新建一个Web API
工程,使用NuGet
引入如下组件:
Autofac
Autofac.Extensions.DependencyInjection
如果要使用Autofac
代替内置的IoC
容器,首先要对Program.cs
进行修改,代码如下:
using Autofac.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
namespace App
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseServiceProviderFactory(new AutofacServiceProviderFactory()) // Autofac代替内置IoC容器
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
上面加了一句UseServiceProviderFactory(new AutofacServiceProviderFactory())
,该方法可以重写用于创建服务提供程序的工厂,也就是说现在已经将其替换为Autofac
对应的工厂了。
在Startup.cs
文件中,我们可以添加一个ConfigureContainer
方法代替原有的ConfigureServices
方法,代码如下:
using App.Service;
using App.Service.Contract;
using Autofac;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace App
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
}
// Autofac注册接口和类
public void ConfigureContainer(ContainerBuilder builder)
{
builder.RegisterType<CatService>().As<ICatService>().InstancePerLifetimeScope();
builder.RegisterType<DogService>().As<IDogService>().InstancePerLifetimeScope();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
创建一个控制器AnimalController
,在构造函数中注入接口即可,代码如下:
using App.Service.Contract;
using Microsoft.AspNetCore.Mvc;
namespace App.Controllers
{
[Route("api/[controller]/[action]")]
[ApiController]
public class AnimalController : ControllerBase
{
protected readonly ICatService _cat;
protected readonly IDogService _dog;
public AnimalController(ICatService cat, IDogService dog)
{
_cat = cat;
_dog = dog;
}
[HttpGet]
public ActionResult<string> Get()
{
return _cat.Get() + "\n" + _dog.Get();
}
}
}
运行结果如下所示:
This is cat
This is dog
之前的博客介绍过,实际业务中一般会对Autofac
进行单独配置。新建一个类AutofacModule
,代码如下:
using App.Service;
using App.Service.Contract;
using Autofac;
namespace App
{
public class AutofacModule : Module
{
protected override void Load(ContainerBuilder builder)
{
builder.RegisterType<CatService>().As<ICatService>().InstancePerLifetimeScope();
builder.RegisterType<DogService>().As<IDogService>().InstancePerLifetimeScope();
}
}
}
修改一下Startup.cs
文件,代码如下:
using Autofac;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace App
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
}
// Autofac注册接口和类
public void ConfigureContainer(ContainerBuilder builder)
{
builder.RegisterModule(new AutofacModule());
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
运行程序,输出结果也是一样的:
This is cat
This is dog
本文主要介绍了在ASP.NET Core
中使用Autofac
代替内置IoC
容器的方法。相较于内置的IoC
容器,Autofac
功能更加丰富、使用更加灵活,在实际业务中合理使用Autofac
可以极大提升开发效率,同时也更加便于项目后期的维护。