当前位置:网站首页>ASP. Net core using Autofac
ASP. Net core using Autofac
2022-07-21 05:26:00 【When the human stars shine】
ASP.NET Core Use Autofac
asp.net core Use autofac
- install Autofac and Autofac.Extensions.DependencyInjection nuget package
- modify Program class
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseServiceProviderFactory(new AutofacServiceProviderFactory())
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
- modify Startup class , Add... To the class ConfigureContainer Method
Property introduction :
RegisterAssemblyTypes: Register assembly type
AsImplementedInterfaces: Implemented interface
InstancePerDependency: Instance dependencies
PropertiesAutowired: Attribute auto connect ( Attribute auto Injection )
/// <summary>
/// To configure Autofac Container replaces Microsoft DI
/// </summary>
/// <param name="containerBuilder"></param>
public void ConfigureContainer(ContainerBuilder builder)
{
// Single service class registration
builder.RegisterType<UserService>().As<IUserService>().InstancePerLifetimeScope();
// Multiple service classes , Assembly registration //
// This is the assembly service that registers other projects
var basePath = AppContext.BaseDirectory;
//DALService Assembly namespace
string DALPath = Path.Combine(basePath, "GraduationProject.DAL.dll");
Assembly DAL = Assembly.LoadFrom(DALPath);
//BLLService Assembly namespace
string BLLPath = Path.Combine(basePath, "GraduationProject.BLL.dll");
Assembly BLL = Assembly.LoadFrom(BLLPath);
builder.RegisterAssemblyTypes(DAL).InstancePerDependency().PropertiesAutowired();
builder.RegisterAssemblyTypes(BLL).AsImplementedInterfaces().InstancePerDependency().PropertiesAutowired();
// This is to register the assembly service under the same project
builder.RegisterAssemblyTypes(typeof(Program).Assembly)
.Where(t => t.Name.EndsWith("Service"))
.AsImplementedInterfaces()
.InstancePerLifetimeScope();
}
Or new AutofacModelRegister Configuration class
// Inherited from Autofac.Model
public class AutofacModelRegister : Autofac.Module
{
// rewrite Autofac The Conduit Load Method , Register injection here
protected override void Load(ContainerBuilder builder)
{
// The configuration logic is the same as above
builder.RegisterType<UserService>().As<IUserService>();
}
}
// And then in startup Class ConfigureContainer Method , To configure
public void ConfigureContainer(ContainerBuilder builder)
{
// Direct use Autofac Sign up for our custom
builder.RegisterModule(new AutofacModuleRegister());
// Service project assembly
//Assembly service = Assembly.Load("XXX.Service");
// Service interface project assembly
//Assembly iservice = Assembly.Load("XXX.IService");
//builder.RegisterAssemblyTypes(service, iservice).Where(t => t.FullName.EndsWith("Service") && !t.IsAbstract)
//.InstancePerLifetimeScope()
//.AsImplementedInterfaces();
}
Be careful : If the service that needs to be injected doesn't interface , that builder.RegisterAssemblyTypes Just pass an assembly OK 了 . If the service and interface are in the same project , It also needs to transfer two assemblies .
- controller Use in
[ApiController]
[Route("[controller]")]
public class HomeController : ControllerBase
{
private readonly IUserService _userService;
public HomeController(IUserService userService)
{
_userService = userService;
}
[HttpGet]
public IActionResult Index()
{
return Ok(_userService.GetName("Test"));
}
}
Attribute auto Injection
Constructor injection is supported by default , If attribute injection is required , Compare constructor Injection , Attribute injection is added more **PropertiesAutowired() ** function
Be careful : Property injection remember to change the access modifier of the property to the one accessible by the registered class , Otherwise, the injection will fail .
If not public An empty reference will be thrown .
The reason is probably Controller By Mvc Module managed , be not in IOC In container , So in Controller Not available in Autofac Injected instance .
// Solve the above problems , stay Startup Of ConfigureServices Add the following code at the bottom of the method :
// Use ServiceBasedControllerActivator Replace DefaultControllerActivator; // Controller The default is a Mvc Module managed , be not in Ioc In the container . After replacement , Will be placed Ioc In the container .
services.Replace(ServiceDescriptor.Transient<IControllerActivator, ServiceBasedControllerActivator>());
// And then back to our AutofacModuleRegister Inject Controller:
builder.RegisterTypes(GetAssemblyTypes<Startup>(type => typeof(ControllerBase).IsAssignableFrom(type))) .PropertiesAutowired();
边栏推荐
猜你喜欢
随机推荐
Console C # flying chess small project
【el-upload实现一个修改头像的功能】
ASP.NET CORE 自定义中间件
One question per day · 731 My schedule | · array
Introduction to Lua scripting language
oracle常用命令
VS2017修改默认包含目录、库目录
Go atomic operation
Jenkins插件开发——插件的拓展
1.54寸TFT ST7789液晶屏图片如何取模
Create k26 SOM minimum system
QT notes - customized flow layout qflowlayout
AutoJs学习-包名查看器
Go sync package
【Verilog数字系统设计(夏宇闻)----Verilog的基础知识2】
Filebeat 的学习笔记
Don't use the line segment tree to solve all my schedule problems with one idea
Run Keyword If 使用详解
Libra's final fate
ASP.NET Core使用记录3