net core 使用微软默认的依赖注入:Microsoft.Extensions.DependencyInjection
1、声明IServiceCollection扩展
public static class Extensions
{
public static IServiceCollection AddDataIntegrationService(this IServiceCollection services,
IConfiguration configuration)
{
//注入ef code 数据连接为mysql
services.AddDbContext<MyDbContext>(options =>
{
var conn = configuration.GetConnectionString("default");
options.UseMySql(conn, ServerVersion.AutoDetect(conn));
})
//单个类手动注入dapper
.AddScoped<IMyDapperRepository, MyDapperRepository>()
services.Scan(scan =>
//将扫描类型MyDbContext类(可指定任意类)所在的程序集,用来确定在那个程序集使用批量注入
scan.FromAssemblyOf<MyDbContext>()
//批量注入类反缀以“service”结尾的
.AddClasses(classes =>
classes.Where(t => t.Name.EndsWith("service", StringComparison.OrdinalIgnoreCase)))
.AsImplementedInterfaces()
.WithScopedLifetime()
//批量注入类反缀以“dal”结尾的
.AddClasses(classes =>
classes.Where(t => t.Name.EndsWith("dal", StringComparison.OrdinalIgnoreCase)))
.AsImplementedInterfaces()
.WithScopedLifetime()
);
return services;
}
}
2.在program中添加扩展
var builder = WebApplication.CreateBuilder(args);
builder.Services
.AddDataIntegrationService(builder.Configuration);
3.使用示例
/// <summary>
/// 声明以"Service"为后缀的类接口
/// </summary>
public interface IOrderService
{
Task Add(long Id);
}
/// <summary>
/// 声明以"Service"为后缀的实现类
/// </summary>
public class OrderService : IOrderService
{
public async Task Add(long Id)
{
// todo..
}
}
/// <summary>
/// 调用示例
/// </summary>
public class Order
{
private readonly IOrderService _orderService;
public Order(IOrderService orderService)
{
_orderService = orderService;
}
public async Task Add(long Id)
{
await _orderService.Add(Id);
}
}