Autofac配置
ASP.NET Core提供依赖注入,但对于稍复杂一些的情况,用Autofac更友好。
Startup添加以下代码
1 public void Configure(IApplicationBuilder app, IWebHostEnvironment env) 2 { 3 …… 4 this.AutofacContainer = app.ApplicationServices.GetAutofacRoot(); 5 } 6 7 public ILifetimeScope AutofacContainer { get; private set; } 8 9 // ConfigureContainer is where you can register things directly 10 // with Autofac. This runs after ConfigureServices so the things 11 // here will override registrations made in ConfigureServices. 12 // Don't build the container; that gets done for you by the factory. 13 public void ConfigureContainer(ContainerBuilder builder) 14 { 15 // Register your own things directly with Autofac here. Don't 16 // call builder.Populate(), that happens in AutofacServiceProviderFactory 17 // for you. 18 builder.RegisterModule(new ServiceModule()); 19 } 20 21 class ServiceModule : Autofac.Module 22 { 23 protected override void Load(ContainerBuilder builder) 24 { 25 var bll = Assembly.Load(new AssemblyName("Square.Service")); 26 builder.RegisterAssemblyTypes(bll) 27 .Where(t => t.Name.EndsWith("Service")) 28 .AsImplementedInterfaces(); 29 } 30 }View Code
Program添加.UseServiceProviderFactory(new AutofacServiceProviderFactory())
Host.CreateDefaultBuilder(args) .UseServiceProviderFactory(new AutofacServiceProviderFactory()) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); });
Areas配置
app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "System", pattern: "{area:exists}/{controller}/{action=Index}/{id?}"); endpoints.MapControllerRoute( name: "default", pattern: "{controller=Login}/{action=Index}/{id?}"); });
2. 在控制器头上标记Areas特性
[Area("System")] public class RoleController : Controller
注意:Views等静态文件的Build Action应为Content
初始化数据库
namespace MvcMovie.Models { public static class SeedData { public static void Initialize(IServiceProvider serviceProvider) { using (var context = new MvcMovieContext( serviceProvider.GetRequiredService< DbContextOptions<MvcMovieContext>>())) { // Look for any movies. if (context.Movie.Any()) { return; // DB has been seeded } context.Movie.AddRange( new Movie { Title = "When Harry Met Sally", ReleaseDate = DateTime.Parse("1989-2-12"), Genre = "Romantic Comedy", Price = 7.99M }, new Movie { Title = "Ghostbusters ", ReleaseDate = DateTime.Parse("1984-3-13"), Genre = "Comedy", Price = 8.99M } ); context.SaveChanges(); } } } }View Code
public class Program { public static void Main(string[] args) { var host = CreateHostBuilder(args).Build(); using (var scope = host.Services.CreateScope()) { var services = scope.ServiceProvider; try { SeedData.Initialize(services); } catch (Exception ex) { var logger = services.GetRequiredService<ILogger<Program>>(); logger.LogError(ex, "An error occurred seeding the DB."); } } host.Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); }View Code
参考链接:
https://docs.microsoft.com/zh-cn/aspnet/core/tutorials/first-mvc-app/working-with-sql?view=aspnetcore-5.0&tabs=visual-studio
https://docs.autofac.org/en/latest/integration/aspnetcore.html#asp-net-core-3-0-and-generic-hosting