Webapi(.net6) 批量服务注册

如果不考虑第三方库,如Autofac这种进行服务注入,通过本身的.Core Weabpi实现的,总结了两种实现方法,

1.一种是参考abp框架里面的形式;

1.1 新建个生命周期的文件夹:

三个接口分别为:

csharp 复制代码
public interface IScopedDependency
{
}
csharp 复制代码
public interface ISingletonDependency
{
}
csharp 复制代码
 public interface ITransientDependency
 {
 }

在实现类中使用如下:

csharp 复制代码
 public interface IUserService
 {
 }

 public class UserService : IUserService, ITransientDependency
 {
 }

1.2 建立个批量服务注册的扩展方法:

csharp 复制代码
public static class ConfigSservice
{
    public static void BatchAddServices(this IServiceCollection services, string assemblyString)
    {
        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);
            }
        }
    }
}

在Programe下注册:

csharp 复制代码
builder.Services.BatchAddServices("WebApi6");

2.第二种通过特性方法:

2.1 新建个注入特性类:

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

使用方法如下:

csharp 复制代码
  public interface IUserService
  {
  }

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

2.2 扩展方法如下:

csharp 复制代码
public static class DependencyInjection
{
    public static void AddServices(this IServiceCollection services, string assemblyName)
    {
        var assembly = Assembly.Load(assemblyName);
        if (assembly != null)
        {
            var types = assembly.GetTypes().Where(s => s.IsClass && !s.IsAbstract).ToList();
            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));
            }
        }
    }
}
csharp 复制代码
builder.Services.AddServices("WebApi6");

如有不对或者建议,欢迎提出指正!

相关推荐
学以智用3 天前
C# Console App(控制台应用)模板详解
.net
宝桥南山4 天前
.NET 11 - 尝试一下Minimal API中的异步验证新特性
microsoft·微软·c#·asp.net·.net·.netcore
无风听海4 天前
深入理解.NET中的 Lazy<T>
服务器·php·.net
海盗12344 天前
微软技术日报 2026-10-14:十月补丁 1411 个漏洞,.NET 11 交出 RC2
人工智能·microsoft·机器人·aigc·.net
学以智用4 天前
.NET WinForms / WPF / Blazor 模板详解
.net
黄一一9112434 天前
吾爱大佬开发,离线可用!PDF文件处理工具,本地网页版文件-浏览器里就能搞定,所有操作系统可用
windows·安全·阿里云·pdf·.net·开源软件
慧都小妮子5 天前
MSG 附件太占内存?Aspose.Email for .NET 26.9 延迟加载
c#·.net·aspose·内存优化·延迟加载·aspose.email·附件内存
学以智用5 天前
ASP.NET Core 项目模板详解:Web应用 / Web API / MVC / Razor Pages
.net
IT规划师5 天前
MQTT实战 - 用了8年MQTT,我为什么还要重新系统啃一遍(一)
物联网·.net