问题描述
使用 MVC5,创建一个对所有层都有引用的引导程序项目非常容易,从而将 UI 层与对基础架构逻辑的引用解耦.该项目将包含启动配置逻辑,例如设置 IoC 容器.
Using MVC5, it has been very easy to create a bootstrapper project that had references to all layers, thus decoupling the UI layer from references to, lets say, infrastructure logic. The project would contain startup configuration logic, such as setting up the IoC container.
这样做的方法是定义一个启动类:
The way to do this was to define a startup class:
public class Startup
{
public static void Start()
{
// startup configuration (IoC etc) goes here
}
}
然后在AssemblyInfo.cs
中添加一行:
[assembly: PreApplicationStartMethod(typeof(Startup), "Start")]
不幸的是,这种方法不再适用于 asp.net 5.我简要查看了文档,但我发现框架在 Web 项目中查找名为 Startup 的类.
Unfortunatelly, this approach no longer works with asp.net 5. I had a brief look at the documentation but all I found out was that the framework looks for a class named Startup within the Web project.
我还查看了 Microsoft.AspNet.Hosting
源代码 似乎负责查找 Startup 类.我可以看到对配置类的一些引用,因此有可能通过使用某种配置设置来加载程序集,但我无法确认或确定哪个设置.
I also had a look within the Microsoft.AspNet.Hosting
source code which seems to be responsible for finding the Startup class. I can see some references to the configuration class, so there is a chance that the assembly can be loaded by using some kind of configuration setting, but I couldn't confirm this or determine which setting.
另外,如果这是真的,当文件本身在 Startup 类中加载时,如何使用 config.json
文件确定 Startup 类?是否有用于配置启动程序集的不同选项,例如使用环境变量?
Also, if this is true, how could the Startup class be determined by using the config.json
file, when the file itself is being loaded within the Startup class? Are there different options for configuring the startup assembly, like for example using an environment variable?
推荐答案
你可以改变WebHostBuilder
会寻找启动类型.
You can change the assembly where the WebHostBuilder
will look for the startup type.
将名称为 Microsoft.AspNet.Hosting.ini
的 INI 配置文件添加到您的 wwwroot
文件夹,其内容如下:
Add an INI config file with the name Microsoft.AspNet.Hosting.ini
to your wwwroot
folder with the following contents:
[Hosting]
Application = App.Bootstrapper
其中 App.Bootstrapper
是您的应用引导程序项目的命名空间.
Where App.Bootstrapper
is the namespace of your application bootstrapper project.
不过,启动类必须看起来相同,例如使用 ConfigureServices
和 Configure
:
The startup class will have to look the same though, e.g. with ConfigureServices
and Configure
:
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
// ...
}
public void Configure(IApplicationBuilder app)
{
// ...
}
}
如果你好奇,可以看看确定启动类型的逻辑这里.如果我们在 INI 文件中指定 Hosting:Application
键,它将使用该值代替 appEnvironment.ApplicationName
.
If you're curious, you can see the logic for determining the startup type here. If we specify the Hosting:Application
key in the INI file, it will use that value in stead of appEnvironment.ApplicationName
.
这篇关于在 ASP.NET 5 和 MVC 6 中将启动配置与 Web 项目分离的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!