您的位置:首页 > 编程语言 > ASP

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

2022-05-10 13:34 916 查看 https://www.cnblogs.com/sports

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/

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐