最近自学.net core 就用了autofac这个东东 不多说 直接上代码
首先在vs2017中创建一个.net core的项目 ,选着web空项目就好,然后在nuget里面安装着最新最稳定的两个程序包 。
安装之后接着就是配置问题了。在项目的Startup.cs文件里面配置。把ConfigureServices的返回类型改为IServiceProvider,然后在再ConfigureServices里面加上
var builder = new ContainerBuilder();//实例化 AutoFac 容器
builder.Populate(services);
ApplicationContainer = builder.Build();
并且还要返回 return new AutofacServiceProvider(ApplicationContainer);
好了 配置就完成了,然后就是注册实例
builder.RegisterType<StudyService>().As<IStudyService>();这就是autofac的注册实例了
然后完全配置下来就是
public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public IContainer ApplicationContainer { get; private set; } public IServiceProvider ConfigureServices(IServiceCollection services) { services.AddMvc(); //var builder = new ContainerBuilder(); //builder.RegisterType<StudyService>().As<IStudyService>(); //builder.Populate(services); //this.ApplicationContainer = builder.Build(); //return new AutofacServiceProvider(this.ApplicationContainer); var builder = new ContainerBuilder();//实例化 AutoFac 容器 builder.RegisterType<StudyService>().As<IStudyService>(); //注册实例 builder.Populate(services); ApplicationContainer = builder.Build(); return new AutofacServiceProvider(ApplicationContainer);//第三方IOC接管 core内置DI容器 } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseBrowserLink(); app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); } }
说的简单,不深入,今天才接触这个,希望对大家有帮助