接口层和实现层
image.png1.创建接口层(Interface) 和 实现层(Service)
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());
});
}
}
}
网友评论