.net Core Autofac稍微高級一點的方法

前情摘要

前段時間寫了autofac的注入可是每次都須要去修改startup這應該不是你們想要的。json

至少不是我想要的。ide

網上有朋友說能夠建立一個基礎類來時間。測試

好了吹牛時間結束咱們開始乾點正事。網站

建立Autofac-Base類

對對對。在網站項目下建立一個文件夾,名字Autofacui

而後建立一個類 Base (建立類的快捷鍵ctrl+alt+a)this

而後就變成了這個樣子spa

Base.cs代碼以下(由於使用了另一個項目因此說和上一篇的interface對不上你們自行修改下。)code

    public class Base : Module
    {
        protected override void Load(ContainerBuilder builder)
        {
            //注入測試服務
            builder.RegisterType<Infrastructure.Repositories.UserInfoRepository>().As<Core.Interfaces.IUserInfoRepository>();
            builder.RegisterType<Infrastructure.Repositories.CaseInfoRepository>().As<Core.Interfaces.ICaseInfoRepository>();

        }
    }

 

 

修改Startup代碼

這是原來的樣子blog

    public void ConfigureServices(IServiceCollection services)

咱們要改爲這個樣子get

        public IContainer ApplicationContainer { get; private set; }
        // This method gets called by the runtime. Use this method to add services to the container.
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            //返回的void 修改成 IServiceProvider 這是爲了讓第三方Ioc容易接管通道 具體在第幾層怎麼實現我沒有深刻研究  
            services.AddMvc();
            var builder = new ContainerBuilder();//實例化 AutoFac  容器            
            builder.Populate(services);//管道寄居
            builder.RegisterModule<AutofacModule.Base>();//使用Module 重寫的方式配置 就不須要每次都來修改Startup文件了。後期打算改爲json的。
            //builder.RegisterType<AutofaceTest.Service.Service.UserService>().As<Service.Interface.IUserService>();//UserService注入到IUserService
            ApplicationContainer = builder.Build();//IUserService UserService 構造
            return new AutofacServiceProvider(ApplicationContainer);//將autofac反饋到管道中
        }

 

使用高級屬性全注入方式

這裏我今兒又偷懶不想寫了。呵呵。。2018-09-28 不寫了 09-29寫吧。

結尾

我就是寫一下目錄。 明兒再寫。

相關文章
相關標籤/搜索