.net core没有接口的服务注入

.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();

将特性加入到相应的类上

既可以实现无接口的依赖注入的使用了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值