.net 8项目通过Autofac获取程序集服务并注册

首先新建一个AutofacModuleRegister类并继承Autofac.Module。

public class AutofacModuleRegister : Autofac.Module

 {

     protected override void Load(ContainerBuilder builder)

     {

         var basePath = AppContext.BaseDirectory;

         var servicesDllFile = Path.Combine(basePath, "Services.dll");

         var repositoryDllFile = Path.Combine(basePath, "Repository.dll");

         if (!(File.Exists(servicesDllFile) && File.Exists(repositoryDllFile)))

         {

             var msg = "Repository.dll和service.dll 丢失,因为项目解耦了,所以需要先F6编译,再F5运行,请检查 bin 文件夹,并拷贝。";

             Log.Error(msg);

             throw new Exception(msg);

         }

         // 获取 Service.dll 程序集服务,并注册

         var assemblysServices = Assembly.LoadFrom(servicesDllFile);

         builder.RegisterAssemblyTypes(assemblysServices).AsImplementedInterfaces().InstancePerDependency();

         // 获取 Repository.dll 程序集服务,并注册

         var assemblysRepository = Assembly.LoadFrom(repositoryDllFile);

         builder.RegisterAssemblyTypes(assemblysRepository).AsImplementedInterfaces().InstancePerDependency();

     }

 }

2.在program.cs中注册自定义的Autofac配置文件。

var builder = WebApplication.CreateBuilder(args);

// 1、配置host与容器

builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory())

            .ConfigureContainer<ContainerBuilder>(builder =>

            {

              builder.RegisterModule(new AutofacModuleRegister());

            });

 源码地址:https://github.com/cplmlm/BasicFramework

posted on 2024-07-01 18:32  一只小小的程序猿  阅读(107)  评论(0编辑  收藏  举报