.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");
自此就可以批量注册服务了!如有不对的地方,欢迎指出!