【BlogBook书】3、Autofac:依赖注入

2024-01-15 17:39:00 浏览数 (1)

整个框架已经做到了基于类库dll程序集级别的服务自动注册。

不需要自己单独做处理,只要在对应的分层中,写入.cs文件即可使用对应的服务。

一、相关的依赖注入配置

代码语言:javascript复制
builder.Host
    .UseServiceProviderFactory(new AutofacServiceProviderFactory())
    .ConfigureContainer<ContainerBuilder>(builder =>
    {
        builder.RegisterModule(new AutofacModuleRegister());
        builder.RegisterModule<AutofacPropertityModuleReg>();
    })

程序集dll批量注册

代码语言:javascript复制
var servicesDllFile = Path.Combine(basePath, "Blog.Core.Services.dll");
 var repositoryDllFile = Path.Combine(basePath, "Blog.Core.Repository.dll");
 
 builder.RegisterGeneric(typeof(BaseRepository<>)).As(typeof(IBaseRepository<>)).InstancePerDependency();//注册仓储
 builder.RegisterGeneric(typeof(BaseServices<>)).As(typeof(IBaseServices<>)).InstancePerDependency();//注册服务

 // 获取 Service.dll 程序集服务,并注册
 var assemblysServices = Assembly.LoadFrom(servicesDllFile);
 builder.RegisterAssemblyTypes(assemblysServices)
     .AsImplementedInterfaces()
     .InstancePerDependency()
     .PropertiesAutowired()
     .EnableInterfaceInterceptors()       //引用Autofac.Extras.DynamicProxy;
     .InterceptedBy(cacheType.ToArray()); //允许将拦截器服务的列表分配给注册。// 获取 Repository.dll 程序集服务,并注册
 var assemblysRepository = Assembly.LoadFrom(repositoryDllFile);
 builder.RegisterAssemblyTypes(assemblysRepository)
     .AsImplementedInterfaces()
     .PropertiesAutowired()
     .InstancePerDependency();

二、各个分层相关代码规则

1、Repository仓储层

Repository仓储层已经被弱化,主要是有一个仓储基类和基类接口,不用再每一个仓储都写类文件了,通过泛型基类注入。

代码语言:javascript复制
IBaseRepository<Guestbook> dal

2、在Service服务层

在Service服务层注入仓储Repository实例,服务层也同样统一了服务基类和基类接口,如果需要使用某个表数据,直接新建该表的服务类

代码语言:javascript复制
public class DepartmentServices : BaseServices<Department>, IDepartmentServices
{

}

当然,如果这个服务中,需要用其他的仓储,可以直接注册

代码语言:javascript复制
public class GuestbookServices : BaseServices<Guestbook>, IGuestbookServices
  {
      private readonly IUnitOfWorkManage _unitOfWorkManage;
      private readonly IBaseRepository<PasswordLib> _passwordLibRepository;

      private readonly IPasswordLibServices _passwordLibServices;

      public GuestbookServices(IUnitOfWorkManage unitOfWorkManage, IBaseRepository<Guestbook> dal, IBaseRepository<PasswordLib> passwordLibRepository, IPasswordLibServices passwordLibServices)
      {
          _unitOfWorkManage = unitOfWorkManage;
          _passwordLibRepository = passwordLibRepository;
          _passwordLibServices = passwordLibServices;
  }

3、在Controller控制层注入服务Service实例

代码语言:javascript复制
public class ModuleController : BaseApiController
{
    readonly IModuleServices _moduleServices;
    readonly IUser _user;


    public ModuleController(IModuleServices moduleServices, IUser user)
    {
        _moduleServices = moduleServices;
        _user = user;
    }
}

三、Controller层同时支持属性注入

类似与Springboot的属性注入,BlogCore也同样支持

1、相关配置

代码语言:javascript复制
public class AutofacPropertityModuleReg : Autofac.Module
 {
     protected override void Load(ContainerBuilder builder)
     {
         var controllerBaseType = typeof(ControllerBase);
         builder.RegisterAssemblyTypes(typeof(Program).Assembly)
             .Where(t => controllerBaseType.IsAssignableFrom(t) && t != controllerBaseType)
             .PropertiesAutowired();

     }
 }

2、直接使用

代码语言:javascript复制
public class BlogController : BaseApiController
 {
     // 属性注入
     public IBlogArticleServices _blogArticleServices { get; set; }
     
     private readonly ILogger<BlogController> _logger;

     /// <summary>
     /// 构造函数服务注入     
     /// </summary>
     /// <param name="logger"></param>
     /// 
     public BlogController(ILogger<BlogController> logger)
     {
         _logger = logger;
     }
 }

0 人点赞