问题描述
我正在 .net 5 中创建一个演示 API。而且,我在我的类库中创建了一些接口来处理生命周期服务,但不了解在启动文件中自动注册依赖项的代码。
类库:.net 标准 2.1
以下是项目架构:
Demo.Api(.Net Core 5 API 项目)
Demo.Core(.Net 标准类库)
依赖(文件夹)
- ICustomDependency.cs
- ISingletonLifetime.cs
- ITransientLifetime.cs
- IMultiInstanceDependency.cs
Demo.Common(.Net Standard 类库)(注意我会在这个项目中添加 Demo.Core 引用)
提供者(文件夹)
- SystemSettingsProvider.cs
服务(文件夹)
- IProductService.cs
助手(文件夹)
- IFileHelper.cs
这是我的界面设计:
// Interface to apply to an object that will be registered into IOC at startup defaults to per-request lifetime
public interface ICustomDependency
{
}
//Interface to apply to register it in to IOC with a Singleton lifetime.</summary>
public interface ISingletonLifetime : ICustomDependency
{
}
//Interface to apply to get a new instance every time you get it from the IOC container.</summary>
public interface ITransientLifetime: ICustomDependency
{
}
public interface IMultiInstanceDependency : ICustomDependency
{
}
这是我希望使用的方式:
public class SystemSettingsProvider: ISingletonLifetime,ICustomDependency
{
//my methods will go here
}
public interface IFileHelper :
ITransientLifetime,ICustomDependency,IMultiInstanceDependency
{
void Print();
}
public interface IProductService: ISingletonLifetime,ICustomDependency
{
//method declarations will go here
}
现在我正在尝试在“Startup.cs”类中的“Demo.Api”项目中编写代码,以便解决所有依赖项 就像一生一样。例如,如果任何接口或类实现了“ISingletonLifetime”,那么它应该被解析为单例。 类似 services.AddSingleton 的东西。同样,如果任何类或接口具有“ITransientLifetime”,那么它应该以暂时的方式解决。
以下是我的 “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.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1",new OpenApiInfo { Title = "WebApplication2",Version = "v1" });
});
}
// 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.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json","WebApplication2 v1"));
}
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
我应该在 Startup.cs 文件中编写什么代码? 有人可以帮我吗?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)