【发布时间】:2021-10-11 09:10:44
【问题描述】:
我们公司的项目有一个模板,他们在另一个类中编写 AddTransient() 方法。我想知道如何把 ConfigureServices 的启动方法放到另一个类中。
看到我们有一个非常简单的启动项目,如下所示:
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.AddControllers();
services.AddTransient<LocationService, LocationService>();
services.AddTransient<PersonService, PersonService>();
services.AddTransient<UserService, UserService>();
services.AddAutoMapper(typeof(Startup));
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
我想将我的(依赖类注册)移动到项目中的另一个类。
所以这将是我的新 Startup.cs:
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.AddControllers();
services.AddAutoMapper(typeof(Startup));
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
这将是我的 ExampleFileName.cs :
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<LocationService, LocationService>();
services.AddTransient<PersonService, PersonService>();
services.AddTransient<UserService, UserService>();
}
【问题讨论】:
-
有基类?这个类甚至可以在不同的库中
-
@Isparia 是的,默认情况下我们在另一个类库项目中拥有它。但我不知道如何在我自己的项目中做到这一点。
-
我不确定我是否完全理解您在这里的要求。但是如果你想在另一个类中配置一些服务,那么你只需要一个可以传入
services对象的方法。这是一个很常见的模式,您可以在此处调用的AddControllers和AddAutoMapper扩展方法中看到它。 -
@DavidG 你能写一个例子吗?
标签: c# asp.net asp.net-core dependency-injection