1. 程式人生 > 其它 >ASP.NET Core MVC 3.1 專案開發記錄

ASP.NET Core MVC 3.1 專案開發記錄

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配置

  1. 新建區域後要在Startup.Config內增加區域路由配置
            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

初始化資料庫

  1. 建立資料庫和架構(.NET Core CLI)
    1. cd DbContext所在專案
    2. dotnet ef migrations add InitialCreate
    3. dotnet ef database update
  2. 資料種子初始化資料(在本地除錯,或引用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