生命周期描述:
Transient 瞬时,每个请求都会创建一个实例,同一个请求,使用多次server,用的不同实例。(轻量级无状态服务尽量用Transient)
Scoped 作用域,在同一个Scoped内只初始化一个实例,同一个请求,使用多次server,就用的同一个实例。(日常用Scoped)
Singleton 单例,整个应用程序生命周期内只创建一个实例。
1、创建Service扩展,创建ServiceAttribute类
注意:ServiceLifetime需要引用 Microsoft.Extensions.DependencyInjection
/// <summary>
/// 定义生命周期
/// 自动注册service
/// </summary>
[AttributeUsage(AttributeTargets.Class)]
public class ServiceAttribute : Attribute
{
public ServiceLifetime LifeTime { get; set; }
/// <summary>
/// 请求模式
/// </summary>
/// <param name="serviceLifetime">默认Scoped</param>
/// Transient 瞬时,每个请求都会创建一个实例,同一个请求,使用多次server,用的不同实例。(轻量级无状态服务尽量用Transient)
/// Scoped 作用域,在同一个Scoped内只初始化一个实例,同一个请求,使用多次server,就用的同一个实例。(日常用Scoped)
/// Singleton 单例,整个应用程序生命周期内只创建一个实例
public ServiceAttribute(ServiceLifetime serviceLifetime = ServiceLifetime.Scoped)
{
LifeTime = serviceLifetime;
}
}
2、注入业务组件,创建ServiceCollectionExpand类
public static class ServiceCollectionExpand
{
/// <summary>
/// 按特性中的生命周期注入业务组件
/// </summary>
/// <param name="service"></param>
public static void AddBusiness(this IServiceCollection service)
{
//获取有ServiceAttribute特性的所有类
List<Type> types = AppDomain.CurrentDomain
.GetAssemblies()
.SelectMany(x => x.GetTypes())
.Where(t => t.IsClass && !t.IsAbstract && t.GetCustomAttributes(typeof(ServiceAttribute), false).Length > 0)
.ToList();
types.ForEach(impl => {
//获取该类所继承的所有接口
Type[] interfaces = impl.GetInterfaces();
//获取该类注入的生命周期
var lifetime = impl.GetCustomAttribute<ServiceAttribute>().LifeTime;
interfaces.ToList().ForEach(i => {
switch (lifetime)
{
case ServiceLifetime.Singleton:
service.AddSingleton(i, impl);
break;
case ServiceLifetime.Scoped:
service.AddScoped(i, impl);
break;
case ServiceLifetime.Transient:
service.AddTransient(i, impl);
break;
}
});
});
}
}
3、在业务逻辑层的Service里引入 [Service()]
4、在Startup.cs文件中引入 services.AddBusiness();