美文网首页
ASP.NET Core 项目实战(接口层和实现层)

ASP.NET Core 项目实战(接口层和实现层)

作者: 彬_哥哥 | 来源:发表于2022-11-24 11:20 被阅读0次
    接口层和实现层

    1.创建接口层(Interface) 和 实现层(Service)

    image.png
    1. 编写 注册接口和实现之间的关系
    image.png
    using Autofac;
    using System.Reflection;
    
    namespace WebApi.Config
    {
        /// <summary>
        /// 
        /// </summary>
        public class AutofacModuleRegister:Autofac.Module
        {
            // 注册接口和实现之间的关系
            protected override void Load(ContainerBuilder builder)
            {
                Assembly interfaceAssembly= Assembly.Load("Interface");
                Assembly serviceAssembly = Assembly.Load("Service");
                builder.RegisterAssemblyTypes(interfaceAssembly, serviceAssembly).AsImplementedInterfaces();
            }
    
        }
    }
    
    

    3.配置注册接口和实现层=》HostBuilderExtend

    using Autofac;
    using Autofac.Extensions.DependencyInjection;
    using SqlSugar;
    using System.Runtime.CompilerServices;
    
    namespace WebApi.Config
    {
        /// <summary>
        /// 注册类-扩展
        /// </summary>
        public static class HostBuilderExtend
        {
            public static void Register(this WebApplicationBuilder app)
            {
                // 1. nuGet 安装 autofac
                app.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
                app.Host.ConfigureContainer<ContainerBuilder>(builder =>
                {
                    #region 注册 sqlsugar
                    builder.Register<ISqlSugarClient>(context =>
                    {
                        SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
                        {
                            //数据库配置地址
                            ConnectionString = "Server=;Database=zxAdminDb;Uid=sa;Pwd=root",
                            DbType = DbType.SqlServer,
                            IsAutoCloseConnection = true
                        });
                        //支持SQL 语句的输出,方便排查问题
                        db.Aop.OnLogExecuted = (sql, par) =>
                        {
                            Console.WriteLine("\r\n");
                            Console.WriteLine($"{DateTime.Now.ToString("yyyyMMdd HH:mm:ss")},Sql语句:{sql}");
                            Console.WriteLine("===================================================");
                        };
                        return db; 
                    });
                    #endregion
    
                    // 注册接口和实现层
                    builder.RegisterModule(new AutofacModuleRegister());
    
                });
            }
    
        }
    }
    
    

    相关文章

      网友评论

          本文标题:ASP.NET Core 项目实战(接口层和实现层)

          本文链接:https://www.haomeiwen.com/subject/bbdzxdtx.html