• .Net Core 最简洁的约定式依赖注入


    .Net Core 最简洁的约定式依赖注入


     github:https://github.com/280780363/guc/tree/master/src/Guc.Kernel/Dependency

    如果大家用过abp框架,应该记得那个很恶心人的DependsOn,对的,需要手动在代码里面去配置依赖关系.然后链式解析依赖关系并注册服务.

    以下基于官方依赖注入框架(顺带提一句,号称最快的autofac,效率都比官方库差得远),实现一句话完成所有的服务注册,不需要你管理依赖关系,不需要你手动注册程序集,不需要你service.Add(...),guc默认使用默认DependencyContext(依赖上下文)解析应用中的程序集.

    // 是的,就一句话,完成整个应用所有项目的服务注册
    services.AddGucKernel();

    Guc提供以下三种约定注入接口:

    ITransient:临时注入,

    ISingleton:全局单例注入,

    IScoped:作用域内单例注入

    只需要继承相应的接口,即可自动注册,例:

        public class UserModel
        {
            public int Id { get; set; }
    
            public string Name { get; set; }
        }
    
        public interface IUserStore : Guc.Kernel.Dependency.ITransient
        {
            List<UserModel> GetAll();
    
            void Update(UserModel userModel);
        }
    
        public class UserStore : IUserStore
        {
            public void Update(UserModel userModel)
            {
                
            }
    
            public List<UserModel> GetAll()
            {
                return new List<UserModel>
                {
                    new UserModel
                    {
                        Id=1,
                        Name="laowang1"
                    },
                    new UserModel
                    {
                        Id=2,
                        Name="laowang2"
                    }
                };
            }
        }

    原理:

    1.使用DependencyContext.Default默认依赖上下文,递归解析包含引用Guc.Kernel的程序集(即可能使用约定注册的程序集);

    2.查找程序集实现了约定接口的类型(ITransient/ISingleton/IScoped);

    3.注册类型.

    核心代码:https://github.com/280780363/guc/blob/master/src/Guc.Kernel/Dependency/ConventionServiceDescriptorProvider.cs

  • 相关阅读:
    一月5日
    一月5日
    面试java工程师的自我介绍(模拟篇)
    Spring Boot Jpa 介绍
    spring+redis做缓存使用
    Spring Boot Web 开发详解
    thymeleaf+spring的简单搭建
    如何搭建 Spring boot
    通用baseDao
    pagehelper的使用
  • 原文地址:https://www.cnblogs.com/gucaocao/p/11527386.html
Copyright © 2020-2023  润新知