zoukankan      html  css  js  c++  java
  • .NetCore下使用Autofac做 IOC 容器

    在.NetCore中使用自带的IOC容器 写注入的时候会写很多,如果要自己封装的话也达不到预期的效果,所以这里采用Autofac来时替代 .NetCore自带的容器

    nuget首先引用Autofac.Extensions.DependencyInjection,关联的Autofac包也一起添加上了

    这里我对DI类的生命周期做了一些特性处理

    在.NetCore自带的容器中 有ScopedSingletonTransient,这里就不对这三个区别做介绍了

    我定义了三种特性,对应这三种方式

     public class ScopedDIAttribute : Attribute
        {
        }
    
    public class SingletonDIAttribute : Attribute
        {
        }
    
     public class TransientDIAttribute : Attribute
        {
        }

    那么在代码中怎么来使用Autofac注入这些对应特性的生命周期,代码如下

    在Startup中ConfigureServices中添加代码,并且修改返回值IServicesProvider ,这里我指定了需要扫描的应用程序集,并且为三种特性注入了对应的生命周期

    var builder = new ContainerBuilder();
                builder.Populate(services);
                var _assably = AppDomain.CurrentDomain.GetAssemblies();
                var _needImpl = _assably.Where(c => c.FullName.StartsWith("ExaminationServicesApplication") 
    || c.FullName.StartsWith("ExaminationServicesDomain")
    || c.FullName.StartsWith("ExaminationServicesInfrastructure")).ToArray(); builder.RegisterAssemblyTypes(_needImpl) .Where(t => t.GetCustomAttribute<ScopedDIAttribute>() != null) .AsImplementedInterfaces() .InstancePerLifetimeScope(); builder.RegisterAssemblyTypes(_needImpl) .Where(t => t.GetCustomAttribute<TransientDIAttribute>() != null) .AsImplementedInterfaces() .InstancePerDependency(); builder.RegisterAssemblyTypes(_needImpl) .Where(t => t.GetCustomAttribute<SingletonDIAttribute>() != null) .AsImplementedInterfaces() .SingleInstance(); builder.RegisterDynamicProxy(); this.ApplicationContainer = builder.Build(); return new AutofacServiceProvider(this.ApplicationContainer);

     builder.RegisterDynamicProxy(); 这个是对AspectCore 针对 Autofac 实现AOP的处理

    做完这些我们只需要在对应的实现类中加入对应的特性即可完成注入,不需要在startup里面大量的写 AddScoped了

    [ScopedDI]
        public class DemoRepository :BaseRepository<School>, IDemoRepository
        {
       }
  • 相关阅读:
    qt做触摸屏演示程序
    sis9280触摸ic 基于rk3288 的安卓4.4的 多点触摸
    自己动手做logo
    把代码做成库文件,防止修改或者查看。
    闲事无聊恳这个
    Python特殊序列d能匹配哪些数字?
    Python正则表达式re.search(r'*{3,8}','*****')和re.search('*{3,8}','*****')的匹配结果为什么相同?
    Python正则表达式re.match(r"(..)+", "a1b2c3")匹配结果为什么是”c3”?
    Python匹配对象的groups、groupdict和group之间的关系
    Python正则表达式处理中的匹配对象是什么?
  • 原文地址:https://www.cnblogs.com/liyouming/p/9857421.html
Copyright © 2011-2022 走看看