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; }