Autofac配置
ASP.NET Core提供依赖注入,但对于稍复杂一些的情况,用Autofac更友好。
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
初始化数据库
- 创建数据库和架构(.NET Core CLI)
- cd DbContext所在项目
- dotnet ef migrations add InitialCreate
- dotnet ef database update
- 数据种子初始化数据(在本地调试,或引用dll完成,只在程序运行第一次时使用)
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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。