首页 > 其他分享 >造轮子之属性注入配合懒加载构建服务抽象基类

造轮子之属性注入配合懒加载构建服务抽象基类

时间:2023-10-12 12:22:25浏览次数:28  
标签:ServiceProvider stringLocalizer LazyGetService null 基类 轮子 注入 public 加载

在前面实现管理API的时候,可以看到我们用的挺多功能是没有通过构造函数注入的。比如缓存DistributedCache,MemoryCache,对象映射Mapper,多语言L,当前用户CurrentUser等等。
这些全都初始化在WheelServiceBase以及WheelControllerBase中,可以通过属性注入完成这个操作,同时为了避免注入太多影响性能,可以配合懒加载实现除IServiceProvider以外的服务注入。

这样做的好处是可以很方便把我们常用的一些工具型服务打包到基类调用,不需要每个业务服务都需要重复注入,同时减少了我们业务服务构造器因为注入越来越臃肿的情况。

上代码:

namespace Wheel.Services
{
    public abstract class WheelServiceBase
    {
        public IServiceProvider ServiceProvider { get; set; }
        public SnowflakeIdGenerator SnowflakeIdGenerator => LazyGetService<SnowflakeIdGenerator>();
        public GuidGenerator GuidGenerator => LazyGetService<GuidGenerator>();
        public IHttpContextAccessor HttpContextAccessor => LazyGetService<IHttpContextAccessor>();

        public IUnitOfWork UnitOfWork => LazyGetService<IUnitOfWork>();

        public IMapper Mapper =>  LazyGetService<IMapper>();
        public IMemoryCache MemoryCache => LazyGetService<IMemoryCache>();

        public IDistributedCache DistributedCache => LazyGetService<IDistributedCache>();
        public ILocalEventBus LocalEventBus => LazyGetService<ILocalEventBus>();
        public IDistributedEventBus DistributedEventBus => LazyGetService<IDistributedEventBus>();
        public ICurrentUser CurrentUser => LazyGetService<ICurrentUser>();
        public IStringLocalizerFactory LocalizerFactory => LazyGetService<IStringLocalizerFactory>();

        private IStringLocalizer _stringLocalizer = null;

        public IStringLocalizer L { 
            get
            {
                if (_stringLocalizer == null)
                    _stringLocalizer = LocalizerFactory.Create(null);
                return _stringLocalizer;
            }
        }

        public T LazyGetService<T>() where T : notnull
        {
            return new Lazy<T>(ServiceProvider.GetRequiredService<T>).Value;
        }
    }
}


namespace Wheel.Controllers
{
    [Authorize("Permission")]
    public abstract class WheelControllerBase : ControllerBase
    {
        public IServiceProvider ServiceProvider { get; set; }
        public SnowflakeIdGenerator SnowflakeIdGenerator => LazyGetService<SnowflakeIdGenerator>();
        public GuidGenerator GuidGenerator => LazyGetService<GuidGenerator>();
        public IUnitOfWork UnitOfWork => LazyGetService<IUnitOfWork>();
        public IMapper Mapper => LazyGetService<IMapper>();
        public IMemoryCache MemoryCache => LazyGetService<IMemoryCache>();

        public IDistributedCache DistributedCache => LazyGetService<IDistributedCache>();
        public ILocalEventBus LocalEventBus => LazyGetService<ILocalEventBus>();
        public IDistributedEventBus DistributedEventBus => LazyGetService<IDistributedEventBus>();
        public ICurrentUser CurrentUser => LazyGetService<ICurrentUser>();
        public IStringLocalizerFactory LocalizerFactory => LazyGetService<IStringLocalizerFactory>();


        private IStringLocalizer _stringLocalizer = null;

        public IStringLocalizer L
        {
            get
            {
                if (_stringLocalizer == null)
                    _stringLocalizer = LocalizerFactory.Create(null);
                return _stringLocalizer;
            }
        }

        public T LazyGetService<T>() where T : notnull
        {
            return new Lazy<T>(ServiceProvider.GetRequiredService<T>).Value;
        }
    }
}

可以看到,只有public IServiceProvider ServiceProvider { get; set; }是通过属性注入的,别的服务都是通过LazyGetService方法获得实例。
LazyGetService则是通过懒加载的方法,调用ServiceProvider.GetRequiredService去获取服务。只有在使用到对应服务时,才会从依赖注入获取对应的服务。

注意,原生依赖注入是不支持使用属性注入功能的,需要第三方依赖注入组件支持,我们使用autofac的时候,若需要属性注入功能,则在注册注入时需要调用PropertiesAutowired()。

轮子仓库地址https://github.com/Wheel-Framework/Wheel
欢迎进群催更。

image.png

标签:ServiceProvider,stringLocalizer,LazyGetService,null,基类,轮子,注入,public,加载
From: https://www.cnblogs.com/fanshaoO/p/17759225.html

相关文章

  • 造轮子之角色管理
    在asp.netcoreidentity中已经有RoleManager,我们只需要封装一下API操作Role即可完成我们角色管理相关功能,这里API打算只提供分页查询,创建以及删除,不提供修改API。实现RoleManageAppServiceIRoleManageAppServicenamespaceWheel.Services.Roles{publicinterfaceIRole......
  • 造轮子之用户管理
    跟角色管理一样,asp.netcoreidentity中已经包含了UserManager,我们只需要简单包装一下逻辑即可完成我们的用户管理相关功能。这里只打算添加分页查询,创建以及修改用户的API,不提供删除API。实现UserManageAppServiceIUserManageAppServicenamespaceWheel.Services.Users{......
  • nittest单元测试框架—加载测试用例的3种方法以及测试报告存储管理
     项目结构 测试用例importunittestclassLoginTestCase(unittest.TestCase):deftest_login_success(self):self.assertEqual({'code':200,'msg':'登录成功'},self.login('kobe','666'))deftest_......
  • 通过unittest加载测试用例的不同方法
    使用python+unitest做自动化测试执行时,执行用例时就涉及测试用例的加载。即如何把测试cases加载到测试suite,然后进行运行。一般把用例加载方法分为两大类:通过unittest.main(),或者通过testsuit。第一种方式使用比较简单,第二种比较灵活多样。 一、测试文件中有测试类,及main......
  • vue项目打包,解决静态资源无法加载和路由加载无效(404)问题
    打包后的项目静态资源无法使用,导致页面空白静态资源无法使用,那就说明项目打包后,图片和其他静态资源文件相对路径不对,此时找到config里面的index.js,在build模块下加入assetsPublicPath:'./', 如下图所示,    在History模式下配合使用nginx运行打包后的项目当刷新当前路......
  • 造轮子之多语言管理
    多语言也是我们经常能用到的东西,asp.netcore中默认支持了多语言,可以使用.resx资源文件来管理多语言配置。但是在修改资源文件后,我们的应用服务无法及时更新,属实麻烦一些。我们可以通过扩展IStringLocalizer,实现我们想要的多语言配置方式,比如Json配置,PO文件配置,EF数据库配置等等......
  • Python 动态加载模块
    Python动态加载模块-lwp-boy-博客园(cnblogs.com)python动态导入模块import_module和重载reload-掘金(juejin.cn)关于Python的动态导入(import)-知乎(zhihu.com)1,啥叫动态加载:动态加载指在程序运行中,动态的加载模块,而不是在运行之前利用import或from...imp......
  • web启动加载资源
    1.struts1plugin创建类实现接口org.apache.struts.action.PlugIn;创建一个空构造函数实现接口方法配置struts-config.xml添加<plug-in/>元素例:publicclassWileyPluginimplementsPlugIn{publicstaticfinalStringPROPERTIES=......
  • 一个页面从输入URL到页面加载显示完成的过程
    当用户在浏览器中输入URL并按下回车时,浏览器会向服务器发送HTTP请求,请求指定的资源。服务器收到请求后,会根据请求的URL返回对应的资源,这通常是一个HTML文件。浏览器收到服务器返回的HTML文件后,会开始解析HTML代码,并在浏览器中构建DOM(DocumentObjcetModal)树。在解析过程中,浏......
  • 造轮子之自定义授权策略
    前面我们已经弄好了用户角色这块内容,接下来就是我们的授权策略。在asp.netcore中提供了自定义的授权策略方案,我们可以按照需求自定义我们的权限过滤。这里我的想法是,不需要在每个Controller或者Action打上AuthorizeAttribute,自动根据ControllerName和ActionName匹配授权。只需要......