内容详情 您现在的位置是: 首页> 其他随笔

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

发布时间:2022-05-11 07:53 已围观:2190

摘要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/

 

声明:本文内容摘自网络,版权归原作者所有。如有侵权,请联系处理,谢谢~
转发:SportSky--https://www.cnblogs.com/sportsky/p/16253178.html

赞一个 (358)