.net core 使用Autofac依赖注入

Startup中:

        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)
        {
            services.Configure<Data>(Configuration.GetSection("Data"));

            services.AddDbContext<ShujuContext>(options =>
                    options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));


            // Add framework services.
            services.AddMvc();

            var builder = new ContainerBuilder();
            builder.RegisterModule(new AutofacModule());
            builder.Populate(services);
            this.ApplicationContainer = builder.Build();
            return new AutofacServiceProvider(this.ApplicationContainer);

        }

AutoFacModule类

    public class AutofacModule : Module
    {
        protected override void Load(ContainerBuilder builder)
        {
            builder.RegisterType<DiTest>().As<IDiTest>();
        }
    }

使用:

        private  IDiTest diTest { get; }

        public HomeController(IDiTest _diTest)
        {
            diTest = _diTest;
        }

 

posted @ 2016-07-25 22:44  韩天伟  阅读(2159)  评论(0编辑  收藏  举报