目前缺乏关于DI主题的文档 - 依赖注入.有人可以帮我理解以下内容:
这些注册有什么区别?
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<IService, Service>();
services.AddScoped<IService, Service>();
services.AddSingleton<IService, Service>();
services.AddInstance(service);
}
Run Code Online (Sandbox Code Playgroud)我一直在将我的存储库类映射到它的接口,同样也用于服务.在这里我可以手动注册它们.但我希望我的代码在运行时动态映射这些代码,这样我就不必在每次创建新的存储库或服务时手动注册它们.我怎样才能做到这一点?
这是我的代码:
public void RegisterDependencies(IServiceCollection services, IConectionSetting connectionSetting)
{
services.AddDbContext<QuantumDbContext>(options => options.UseSqlServer(connectionSetting.Get()));
//services.AddDbContext<TestDbContext>(options => options.UseSqlServer(databaseFactory.ConnectionString));
services.AddTransient<IDatabaseFactory, DatabaseFactory>();
services.AddTransient<IDbContext, TestDbContext>();
services.AddTransient<IDbContext, QuantumDbContext>();
services.AddTransient<IUnitOfWorkManager, UnitOfWorkManager>();
services.AddTransient<IRepository<CodeTable>, Repository<CodeTable>>();
services.AddTransient<IRepository<Country>, Repository<Country>>();
services.AddTransient<IRepository<State>, Repository<State>>();
services.AddTransient<IRepository<City>, Repository<City>>();
services.AddTransient<ICodeTableService, CodeTableService>();
services.AddTransient<ICountryService, CountryService>();
}
Run Code Online (Sandbox Code Playgroud) c# dependency-injection entity-framework-core asp.net-core-mvc asp.net-core