返回顶部

Asp.Net Core中注入泛型接口的依赖项

1、扩展批量注入类

public static class ServicesExtersion
    {
        public static void AddClassesAsImplementedInterface(
            this IServiceCollection services
            , Assembly assembly
            , Type compareType
            , ServiceLifetime lifetime = ServiceLifetime.Scoped)
        {
            assembly.GetTypesAssignableTo(compareType).ForEach((type) =>
            {
                foreach (var implementedInterface in type.ImplementedInterfaces)
                {
                    switch (lifetime)
                    {
                        case ServiceLifetime.Scoped:
                            services.AddScoped(implementedInterface, type);
                            break;
                        case ServiceLifetime.Singleton:
                            services.AddSingleton(implementedInterface, type);
                            break;
                        case ServiceLifetime.Transient:
                            services.AddTransient(implementedInterface, type);
                            break;
                    }
                }
            });
        }

        public static List<TypeInfo> GetTypesAssignableTo(this Assembly assembly, Type compareType)
        {

            var typeInfoList = assembly.DefinedTypes.Where(x => x.IsClass
                                && !x.IsAbstract
                                && x != compareType
                                && x.GetInterfaces().Any(i => i.IsGenericType
                                && i.GetGenericTypeDefinition() == compareType))?.ToList();

            return typeInfoList;
        }
    }

2、Startup注入

// 注入泛型依赖项
            services.AddClassesAsImplementedInterface(Assembly.Load("WebApplication2"), typeof(IServices<>));

3、接口实现类

public class User
    {
    }

public class Role
    {
    }

public class UserServices: IServices<User>
    {
        public async Task<string> GetData()
        {
            return await Task.FromResult("User服务实现类");
        }

        public async Task<User> GetObj()
        {
            return await Task.FromResult(new User());
        }
    }

public class RoleServices:IServices<Role>
    {
        public async Task<string> GetData()
        {
            return await Task.FromResult("Role服务实现类");
        }

        public async Task<Role> GetObj()
        {
            return await Task.FromResult(new Role());
        }
    }

 public interface IServices<T>
    {
        Task<string> GetData();

        Task<T> GetObj();
    }

4、controll控制器实现

public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;
        private readonly IServices<User> _userServices;
        private readonly IServices<Role> _roleServices;

        public HomeController(ILogger<HomeController> logger, IServices<User> userServices, IServices<Role> roleServices)
        {
            _logger = logger;
            _userServices= userServices;
            _roleServices= roleServices;
        }

        public async Task<IActionResult> Index()
        {
            {
                _logger.LogInformation($"{await _userServices.GetData()}");
                _logger.LogInformation($"{await _userServices.GetObj()}");
            }

            {
                _logger.LogInformation($"{await _roleServices.GetData()}");
                _logger.LogInformation($"{await _roleServices.GetObj()}");
            }

            return View();
        }
    }

 项目整体结构

 

 

 

友情链接:https://www.codenong.com/39320265/

 

posted @ 2022-05-10 13:34  SportSky  阅读(1050)  评论(0编辑  收藏  举报
作者:SportSky 出处: http://www.cnblogs.com/sportsky/ 本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。如果觉得还有帮助的话,可以点一下右下角的【推荐】,希望能够持续的为大家带来好的技术文章!想跟我一起进步么?那就【关注】我吧。