Я добавил новый проект API, использующий ядро dot net 3, и у меня уже есть проект библиотеки классов, использующий стандартную структуру dot net. Сначала он содержит базу данных BAL + EF. Проблема в том, что я хочу вызывать функции из BAL, и строка соединения с БД должна передаваться из проекта API в проект BAL.
Запуск API:
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)
{
//string connectionString = Configuration.GetConnectionString("CoreContext");
//services.AddDbContextPool<DbContext>(options => options.UseSqlServer(connectionString));
services.AddScoped<CoreContext>(_ => new CoreContext(Configuration.GetConnectionString("CoreContext")));
string authorityURL = this.Configuration.GetValue<string>("AuthorityServer:URL");
string ApiName = this.Configuration.GetValue<string>("AuthorityServer:ResourceName");
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddIdentityServerAuthentication(o =>
{
o.Authority = authorityURL;
o.ApiName = ApiName;
o.ApiSecret = "xretail";
o.RequireHttpsMetadata = false;
});
services.AddAuthorization();
services.AddControllers();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseAuthentication();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
//using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope())
//{
// serviceScope.ServiceProvider.GetService<DbContext>().Database.Migrate();
//}
}
И контроллер API
[Route("api/[controller]")]
[ApiController]
public class ShoutsController : ControllerBase
{
private readonly IConfiguration Configuration;
public ShoutsController(IConfiguration config)
{
Configuration = config;
}
[HttpGet]
[Authorize]
public IActionResult Get()
{
using (var customerBL = new CustomerBL(new XRetail.Core.BL.DataAccess.CoreContext(Configuration.GetConnectionString("CoreContext"))))
{
var username = User.Claims.First(x => x.Type == "email").Value;
var customer = customerBL.GetCustomers()/*.FirstOrDefault(x => x.Email == username)*/;
if (customer == null)
{
return NotFound();
}
return Ok(customer);
}
}
}
Затем я создал частичный контекст
public partial class CoreContext
{
public CoreContext(String ConnectionString) : base(ConnectionString)
{
Interlocked.Increment(ref NoOfConexts);
}
}
public partial class CoreContextFactory : IDbContextFactory<CoreContext>
{
public CoreContext Create()
{
return new CoreContext("metadata=res://*/DataAccess.CoreContext.csdl|res://*/DataAccess.CoreContext.ssdl|res://*/DataAccess.CoreContext.msl;provider=System.Data.SqlClient;provider connection string="data source=192.168.1.221;initial catalog=XRetail-PartnerMerge-v1.0;persist security info=True;user id=xretail_admin;password=Xretail@4321;MultipleActiveResultSets=True;App=gabr"");
}
}
И использовал внутри конструктора Customer
public CustomerBL(CoreContext context)
{
Context = context;
}