在Asp.Net.Core之前,当我托管我的WEBAPI代码时,我使用Unity和Unity.configuration来定义我的DI。
这样的事情:
<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
<container>
<register type="MyLibrary.Interfaces.IDepartmentManager, MyLibrary"
mapTo="MyLibrary.DepartmentManager, MyLibrary" />
<register type="MyLibrary.Interfaces.IFtpFileSender, MyLibrary"
mapTo="MyLibrary.FtpFileSender, MyLibrary" />
</container>
</unity>
现在我进入了AspNetCore。
我想出了“编码”是如何工作的。
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace MyNamespace
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
/* THE MAGIC !! */
services.AddTransient<MyLibrary.Interfaces.IDepartmentManager, MyLibrary.DepartmentManager>();
services.AddTransient<MyLibrary.Interfaces.IFtpFileSender, MyLibrary.FtpFileSender>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMvc();
}
}
}
有没有办法使用配置文件(MyDependencies.json)或新的/烘焙依赖引擎?
这是我发现的最接近的事情
https://csharp.christiannagel.com/2016/08/16/diwithconfiguration/
但不是直接命中。