如果不考虑第三方库,如Autofac这种进行服务注入,通过本身的.Core Weabpi实现的,总结了两种实现方法,
1.一种是参考abp框架里面的形式;
1.1 新建个生命周期的文件夹:
三个接口分别为:
public interface IScopedDependency
{
}
public interface ISingletonDependency
{
}
public interface ITransientDependency{}
在实现类中使用如下:
public interface IUserService{}public class UserService : IUserService, ITransientDependency{}
1.2 建立个批量服务注册的扩展方法:
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);elseservices.AddSingleton(inter, type);}}}
}
在Programe下注册:
builder.Services.BatchAddServices("WebApi6");
2.第二种通过特性方法:
2.1 新建个注入特性类:
[AttributeUsage(AttributeTargets.Class, Inherited = false,AllowMultiple = false)]public class InjectServiceAttribute : Attribute{public Type ServiceType { get; set; }public ServiceLifetime Lifetime { get; set; }}
使用方法如下:
public interface IUserService{}[InjectService(Lifetime = ServiceLifetime.Transient, ServiceType = typeof(IUserService))]public class UserService{}
2.2 扩展方法如下:
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));}}}
}
builder.Services.AddServices("WebApi6");
如有不对或者建议,欢迎提出指正!