.net core中依赖注入的三种生命周期
要实现没有接口的依赖注入,首先当然是要了解依赖注入是什么了。网上资料还是很多的,这里不详细写了,具体写一下没有写接口,但又想实现依赖注入,怎么的具体实现。
首先要知道生命周期.net core提供了三种生命周期,大部分默认情况下基本上是第二种。
public enum ScopeEnum
{
// 整个应用程序生命周期中只有1个实例
Singleton,
//在同一个Scope内只初始化一个实例,可以理解为在同一个scope里只有一个实例
Scope,
// 每次创建的对象都是不同的
Transient
}
第二步 找出service
使用特性的方法找到需要给类实现接口的方法
var serviceTypes = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(s => s.DefinedTypes.Where(t => t.GetCustomAttribute<ServiceAttribute>(false) != null))
.ToArray();
第三步 循环特性,对获取到的集合进行依赖注入
通过特性找到是否还存在接口以及生命周期的类型
下划线_是7.0的特性,表示丢弃,不再使用的意思
foreach(var type in serviceTypes)
{
var serviceAttribute = type.GetCustomAttribute<ServiceAttribute>();
var scopeType = serviceAttribute?.ScopeType ?? ScopeEnum.Scope;
var interfaceType = serviceAttribute?.InterfaceType ?? type.GetInterface($"I{type.Name}");
var _ = interfaceType == null ? AddInstance(scopeType, service, type)
: AddByInterface(scopeType, service, interfaceType, type);
}
return service;
特性设置很简单,就是新建一个类,以及在构造器里实现参数设置
public class ServiceAttribute : Attribute
{
public ScopeEnum ScopeType { get; set; }
public Type InterfaceType { get; set; }
public ServiceAttribute(Type interfaceType=null,ScopeEnum scope = ScopeEnum.Scope)
{
InterfaceType= interfaceType;
ScopeType = scope;
}
}
之后在ConfigureServices(用于配置依赖注入以在运行时根据依赖关系创建对象)里加入 services.AddIocServiceScanner();
将特性加入到相应的类上
既可以实现无接口的依赖注入的使用了。