.net AutoFac的使用
作者:互联网
.net AutoFac的使用
官方链接
此文仅仅是个人学习记录
ASP .NET CORE
ASP.NET Core 1.1 - 2.2
下面的示例演示了 ASP.NET Core 1.1 - 2.2 使用方法, 你可以调用 WebHostBuilder 的 services.AddAutofac(). 这不适用于ASP.NET Core 3+ 或 .NET Core 3+ generic hosting 支持 - ASP.NET Core 3 需要你直接指定一个service provider factory而不是把它加入进service collection.
public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.ConfigureServices(services => services.AddAutofac())
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
host.Run();
}
}
public class Startup
{
public Startup(IHostingEnvironment env)
{
// In ASP.NET Core 3.0 env will be an IWebHostEnvironment , not IHostingEnvironment.
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
this.Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; private set; }
public ILifetimeScope AutofacContainer { get; private set; }
// ConfigureServices is where you register dependencies and return an `IServiceProvider` implemented by `AutofacServiceProvider`.
// ConfigureServices是注册依赖项并返回实现了“IServiceProvider”的“AutofacServiceProvider”。
// This is the old, not recommended way, and is NOT SUPPORTED in ASP.NET Core 3.0+.
// 这是旧的不推荐的方式,在中ASP.NET 3.0+不受支持。
public IServiceProvider ConfigureServices(IServiceCollection services)
{
// Add services to the collection
// 添加Options服务
services.AddOptions();
// Create a container-builder and register dependencies
// 创建容器生成器并注册依赖项
var builder = new ContainerBuilder();
// Populate the service-descriptors added to `IServiceCollection`
// BEFORE you add things to Autofac so that the Autofac
// registrations can override stuff in the `IServiceCollection`
// as needed
// 在向Autofac添加内容之前,填充添加到“IServiceCollection”的服务描述符,以便Autofac注册可以根据需要覆盖“IServiceCollection”中的内容
builder.Populate(services);
// Register your own things directly with Autofac
// 直接向Autofac注册您自己的东西
builder.RegisterModule(new MyApplicationModule());
AutofacContainer = builder.Build();
// this will be used as the service-provider for the application!
// 这将用作应用程序的服务提供商!
return new AutofacServiceProvider(AutofacContainer);
}
// Configure is where you add middleware.
// You can use IApplicationBuilder.ApplicationServices
// 您可以配置任意中间件。
// 你可以用IApplicationBuilder.ApplicationServices
public void Configure(
IApplicationBuilder app,
ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(this.Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseMvc();
}
}
ASP.NET Core 3.0+ and Generic Hosting
在ASP.NET Core 3.0托管方式发生了变化 并且需要不同的集成方式. 你不能在从 ConfigureServices 中返回 IServiceProvider, 也不能再将你的service provider factory加入到service collection.
下面是ASP.NET Core 3+ 和 .NET Core 3+ generic hosting support的集成方式:
public class Program
{
public static void Main(string[] args)
{
// ASP.NET Core 3.0+:
// The UseServiceProviderFactory call attaches the
// Autofac provider to the generic hosting mechanism.
var host = Host.CreateDefaultBuilder(args)
.UseServiceProviderFactory(new AutofacServiceProviderFactory())
.ConfigureWebHostDefaults(webHostBuilder => {
webHostBuilder
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>();
})
.Build();
host.Run();
}
}
Startup类
在你的Startup类中 (各版本ASP.NET Core基本一致) 你可以使用 ConfigureContainer 访问 Autofac container builder 并且直接使用Autofac注册东西.
public class Startup
{
public Startup(IHostingEnvironment env)
{
// In ASP.NET Core 3.0 `env` will be an IWebHostEnvironment, not IHostingEnvironment.
// 在ASP.NET 3.0“env”将是一个IWebHostEnvironment,而不是IHostingEnvironment。
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
this.Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; private set; }
public ILifetimeScope AutofacContainer { get; private set; }
// ConfigureServices is where you register dependencies. This gets
// called by the runtime before the ConfigureContainer method, below.
// ConfigureServices是注册依赖项的地方。它由运行时在下面的ConfigureContainer方法之前调用。
public void ConfigureServices(IServiceCollection services)
{
// Add services to the collection. Don't build or return
// any IServiceProvider or the ConfigureContainer method
// won't get called.
// 向集合添加服务。不要构建或返回任何IServiceProvider,否则ConfigureContainer方法将不会被调用。
services.AddOptions();
}
// ConfigureContainer is where you can register things directly
// with Autofac. This runs after ConfigureServices so the things
// here will override registrations made in ConfigureServices.
// Don't build the container; that gets done for you by the factory.
// ConfigureContainer是您可以直接向Autofac注册内容的地方。它在ConfigureServices之后运行,因此这里的内容将覆盖在ConfigureServices中进行的注册。别造集装箱,那是工厂帮你做的。
public void ConfigureContainer(ContainerBuilder builder)
{
// Register your own things directly with Autofac, like:
// 直接向Autofac注册您自己的东西,例如:
builder.RegisterModule(new MyApplicationModule());
}
// Configure is where you add middleware. This is called after
// ConfigureContainer. You can use IApplicationBuilder.ApplicationServices
// here if you need to resolve things from the container.
// Configure是您添加中间件的地方。这在ConfigureContainer之后调用。你可以用IApplicationBuilder.ApplicationServices
public void Configure(
IApplicationBuilder app,
ILoggerFactory loggerFactory)
{
// If, for some reason, you need a reference to the built container, you
// can use the convenience extension method GetAutofacRoot.
// 如果出于某种原因,需要对生成的容器进行引用,可以使用方便的扩展方法GetAutofacRoot。
this.AutofacContainer = app.ApplicationServices.GetAutofacRoot();
loggerFactory.AddConsole(this.Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseMvc();
}
}
配置方法命名约定
Configure, ConfigureServices, 和 ConfigureContainer 方法都支持基于你应用中 IHostingEnvironment.EnvironmentName 参数的环境特定命名约定. 默认地, 名称为 Configure, ConfigureServices, 和 ConfigureContainer. 如果你想要环境特定设置, 你可以把环境名称放在 Configure 部分后面, 类似 ConfigureDevelopment, ConfigureDevelopmentServices, 和 ConfigureDevelopmentContainer. 如果方法并不以匹配的环境名称显示, 它会回到默认方法.
这意味着你不必使用 Autofac配置 在生产环境和开发环境之间切换; 你可以在 Startup 中以编程形式设置.
public class Startup
{
public Startup(IHostingEnvironment env)
{
// Do Startup-ish things like read configuration.
// 做一些像读配置这样的启动操作。
}
// This is the default if you don't have an environment specific method.
// 如果没有特定于环境的方法,则这是默认值。
public void ConfigureServices(IServiceCollection services)
{
// Add things to the service collection.
// 添加一些服务
}
// This only gets called if your environment is Development. The
// default ConfigureServices won't be automatically called if this
// one is called.
// 只有在您的环境是开发环境时才调用此函数。如果调用此配置服务,则不会自动调用默认ConfigureServices。
public void ConfigureDevelopmentServices(IServiceCollection services)
{
// Add things to the service collection that are only for the
// development environment.
// 向服务集合中添加只用于开发环境的内容。
}
// This is the default if you don't have an environment specific method.
// 如果没有特定于环境的方法,则这是默认值。
public void ConfigureContainer(ContainerBuilder builder)
{
// Add things to the Autofac ContainerBuilder.
// 向Autofac ContainerBuilder添加内容。
}
// This only gets called if your environment is Production. The
// default ConfigureContainer won't be automatically called if this
// one is called.
// 只有在您的环境是生产环境时才调用此函数。如果调用此容器,则不会自动调用默认的ConfigureContainer。
public void ConfigureProductionContainer(ContainerBuilder builder)
{
// Add things to the ContainerBuilder that are only for the
// production environment.
// 向ContainerBuilder添加仅用于生产环境的内容。
}
// This is the default if you don't have an environment specific method.
// 如果没有特定于环境的方法,则这是默认值。
public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
{
// Set up the application.
// 设置应用程序。
}
// This only gets called if your environment is Staging. The
// default Configure won't be automatically called if this one is called.
// 仅当您的环境正在暂存时才会调用此函数。如果调用此配置,则不会自动调用默认配置。
public void ConfigureStaging(IApplicationBuilder app, ILoggerFactory loggerFactory)
{
// Set up the application for staging.
}
}
标签:Core,AutoFac,ASP,ConfigureServices,使用,Autofac,net,NET,public 来源: https://blog.csdn.net/qq_21960819/article/details/111823170