.Net6 批量注册服务

.net core及其之后的.net版本,注册服务有多张方法,除了微软本身提供的原原生DI容器,还有第三方的各种容器,比如autofac,unity等等。这里,我打算在.net6下自己实现批量注册服务。代码如下:

way1:基于约定(注入服务的实现类对应的接口放在继承的第一位)

1.新建一个生命周期文件夹LifeTime,然后添加三个空接口,代码如下

  public interface ITransientDependency
  {
  }
   public interface IScopedDependency
 {
 }
  public interface ISingletonDependency
 {
 }

2.新建两个服务,代码如下:

 public interface IUserService
 {
     Task<string> GetUserListAsync();
 }
 public class UserService : IUserService, ITransientDependency
 {
     public async Task<string> GetUserListAsync()
     {
         return await Task.FromResult("users");
     }
 }
   public interface IRoleService
   {
   }

   public class RoleService : IRoleService, IScopedDependency
   {
   }
   此处需要注意,把想要注入服务的实现类对应的接口放在继承的第一位,这样后面取接口里面的First即可。

3.新建个批量添加服务的方法,代码如下:

 public class ConfigSservice
 {
     public static void BatchAddServices(IServiceCollection services, string assemblyString = "NetCoreWebApi")
     {
         var assembly = Assembly.Load(assemblyString);
         var types = assembly.GetTypes();
         var list = types.Where(u => u.IsClass && !u.IsAbstract && !u.IsGenericType
         && (typeof(ITransientDependency).IsAssignableFrom(u)
         || typeof(IScopedDependency).IsAssignableFrom(u)
         || typeof(ISingletonDependency).IsAssignableFrom(u))).ToList();
         foreach (var type in list)
         {
             var interfaceList = type.GetInterfaces();
             if (interfaceList.Any())
             {
                 var inter = interfaceList.First();
                 if (typeof(ITransientDependency).IsAssignableFrom(type))
                     services.AddTransient(inter, type);
                 else if (typeof(IScopedDependency).IsAssignableFrom(type))
                     services.AddScoped(inter, type);
                 else
                     services.AddSingleton(inter, type);
             }
         }
     }
 }

4.在Program类下添加如下代码:
ConfigSservice.BatchAddServices(builder.Services, “CoreWebapiDemo”);

way2:基于特性Attribute

1.添加个注入服务特性类

[AttributeUsage(AttributeTargets.Class, Inherited = false,AllowMultiple = false)]
public class InjectServiceAttribute : Attribute
{
    public Type ServiceType { get; set; }
    public ServiceLifetime Lifetime { get; set; }
}

2.在对应实现服务类上使用该特性

public interface IUserService
{
}

[InjectService(Lifetime = ServiceLifetime.Transient, ServiceType = typeof(IUserService))]
public class UserService : IUserService, ITransientDependency
{
}

3.添加程序集古纳于服务注册操作类

public static class DependencyInjection
{
    public static void AddAssembly(this IServiceCollection services, string assemblyName)
    {
        var assembly = Assembly.Load(assemblyName);
        if (assembly != null)
        {
            var types = assembly.GetTypes().Where(s => s.IsClass && !s.IsAbstract);
            foreach (var type in types)
            {
                var injectService = type.GetCustomAttribute<InjectServiceAttribute>();
                if (injectService == null)
                    continue;

                var serviceType = injectService.ServiceType ?? type;
                var implementationType = type;
                var lifetime = injectService.Lifetime;
                services.Add(new ServiceDescriptor(serviceType, implementationType, lifetime));
            }
        }
    }
}

4.注册服务

builder.Services.AddAssembly("CoreWebapiDemo");

自此就可以批量注册服务了!如有不对的地方,欢迎指出!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值