我是在.net6框架下安装autofac。
1.安装这两个包。我现在是安装得最新的的这两个包。
2.新建文件 AutoRegisterService.cs,我有两方面注入;
一:用于Service注入
二:用于仓储注入
using System;
using System.Reflection;
using Autofac;
using ImroApi.IServices;
namespace Api.Ioc
{
/// <summary>
/// Autofac容器扩展
/// </summary>
public static class ContainerBuilderExtensions
{
/// <summary>
/// Autofac自动注入Service层应用
/// </summary>
/// <param name="builder">容器</param>
/// <param name="serviceNameEndsWith">实例名统一已指定名字结尾</param>
public static void AutoRegisterService(this ContainerBuilder builder)
{
//自动注入service
var assemblysServices = Storage.Assemblys.ToArray();
builder.RegisterAssemblyTypes(assemblysServices)
.Where(x => x.Name.EndsWith("Service", StringComparison.OrdinalIgnoreCase))
.AsSelf()//注入自身
.AsImplementedInterfaces()
.InstancePerLifetimeScope()
.PropertiesAutowired(); // 开启属性注入;
builder.RegisterAssemblyTypes(assemblysServices)
.Where(x => x.Name.EndsWith("Repository", StringComparison.OrdinalIgnoreCase))
.AsSelf()//注入自身
.AsImplementedInterfaces()
.InstancePerLifetimeScope()
.PropertiesAutowired(); // 开启属性注入;
//注入控制器
var types = Storage.Assemblys.SelectMany(x => x.GetTypes())
.Where(x => x.IsClass && !x.IsInterface && !x.IsAbstract && !x.IsGenericType);
var controller = typeof(ControllerBase);
var arrControllerType = types.Where(t => controller.IsAssignableFrom(t) && t != controller).ToArray();
builder.RegisterTypes(arrControllerType).PropertiesAutowired();
// 注册 AppSettings
builder.Register(c =>
{
var configuration = c.Resolve<IConfiguration>();
var appSettings = new AppSettings();
configuration.Bind(appSettings);
return appSettings;
}).AsSelf().InstancePerLifetimeScope().PropertiesAutowired();
// configuration绑定当前环境
builder.Register(c =>
{
var configuration = c.Resolve<IConfiguration>();
var environment = new HostingEnvironment();
configuration?.Bind(environment);
return environment;
}).As<IHostEnvironment>().InstancePerLifetimeScope().PropertiesAutowired();
}
}
}
3.注入autofac服务
builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
builder.Host.ConfigureContainer(containerBuilder =>
{
containerBuilder.AutoRegisterService();
});
builder.Services.Replace(ServiceDescriptor.Transient<IControllerActivator, ServiceBasedControllerActivator>());
4.使用 属性注入
一:db等中间件的注入
public ILogger<MaterialService> logger { get; set; }//logger直接注入 我是用的NLOG 其他的我觉得应该也没什么问题,后面有时间试试其他的;
public nbDbcontext _imro { get; set; }//EFCore 的Dbcontext 直接注入
public IConfiguration Configuration { get; set; }//配置直接注入使用
public IHttpContextAccessor _httpContextAccessor { get; set; }//读取http数据直接引入使用
二:Service、Reposity等的注入:
注入 IProductService。当然也可以注入ProductService。
//注入配置
public class AppSettings
{
public Setting setting { get; set; }
}
public class Setting
{
public string host { get; set; }
}
namespace ImroApi.Controllers
{
[Route("api/[controller]")]
[ApiController]
[Authorize]
public class TestController : ControllerBase
{
public IProductService _productService { get; set; }
public AppSettings _config { get; set; }
[HttpGet]
public void Test()
{
var s = _productService.GetCategories();
var _c=_config.setting.host;
}
}
}
4.构造函数注入并使用
public class BaseController : ControllerBase
{
protected readonly NBDbcontext _nb;
protected readonly IConfiguration _configuration;
protected ILogger _logger;
protected readonly IMapper _mapper;
protected readonly IHttpContextAccessor _httpContextAccessor;
protected readonly Commons.Common _common;
protected readonly IAService _aService;
public BaseController(NBDbcontext nb
, IConfiguration configuration
, ILogger logger
, IMapper mapper
, IHttpContextAccessor httpContextAccessor
, Commons.Common common
, IAService aService)
{
_nb= nb;
_configuration = configuration;
_logger = logger;
_mapper = mapper;
_httpContextAccessor = httpContextAccessor;
_common = common;
_aService=aService
}
[HttpGet]
public void Test()
{
var s = _aService.GetCategories();
}
}
以上就是Autofac注入总结。让我们一起变得更强!