Aspnetcore2.0中Entityframeworkcore及Autofac的使用(三)(附Demo)((2018-12-04 10:08)

三,使用Autofac替换原有Ioc

首先安装Autofac两个插件类库:

Autofac

Autofac.Extensions.DependencyInjection

修改Startup.cs替换框架自带IOC:

// This method gets called by the runtime. Use this method to add services to the container.
        //public void ConfigureServices(IServiceCollection services)
        //{
        //    services.AddMvc();
        //    //配置上下文
        //    services.AddDbContext<test1Context>(options => options.UseSqlServer(Configuration.GetConnectionString("connstr")));
        //    //默认IOC实现注入
        //    services.AddScoped(typeof(BookService));
        //}
        public IContainer ApplicationContainer { get; private set; }
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            //配置上下文
            services.AddDbContext<test1Context>(options => options.UseSqlServer(Configuration.GetConnectionString("connstr")));

            //创建Autofac构建器
            var builder = new ContainerBuilder();
            //反射获取业务逻辑类
            var assemblys = Assembly.Load("AspNetCore.Service");
            builder.RegisterAssemblyTypes(assemblys)
                .Where(a => a.Name.EndsWith("Service"))
                .InstancePerLifetimeScope();
            //移植到原有服务
            builder.Populate(services);
            //替换默认容器
            ApplicationContainer = builder.Build();
            //Autofac接管默认IOC
            return new AutofacServiceProvider(ApplicationContainer);
        }

再次运行:

成功完成。

总结:

1.使用Nuget安装类库时需要与Net.Core的版本一致,否则会版本不兼容产生错误。

2.每次生成实体与上下文类,记得要修改上下文类中的代码

3.这个程序只是依赖于类,没有依赖接口,大家可以自行研究

源码下载地址:https://gitee.com/MrLiuDaShuai/Aspnetcore

原文地址:https://www.cnblogs.com/MrLiu90/p/10062758.html