概述: 我有两个项目,一个ASP.NetCore Web API和一个EF 6.1类库。类库包含与我的数据库交互并返回对象的管理器类。
我遵循本教程进行依赖注入,但它没有解决我的项目中的场景,其中EF位于单独的类库中,并且通过管理器类进行交互:
https://docs.microsoft.com/en-us/aspnet/core/data/entity-framework-6
我按照以下方式工作(但我不高兴,因为我不想重载连接字符串):
public class AccountManager
{
private static string ConnectionString = LibDataEntities.ConnectionString;
public static AccountDC AuthenticateAccount(string EmailAddress, string Password)
{
LibData.Model.AccountDC account = null;
using (var db = new LibDataEntities(ConnectionString))
{
var qry = (from accounts in db.Accounts
where accounts.IsAdmin == true
&& accounts.Active == true
&& accounts.Email == EmailAddress
&& accounts.Password == Password
select new LibData.Model.AccountDC
{
Active = accounts.Active,
Email = accounts.Email,
FirstName = accounts.FirstName,
Id = accounts.Id,
IsAdmin = accounts.IsAdmin,
IsSuperAdmin = accounts.IsSuperAdmin,
LastName = accounts.LastName,
LibraryId = accounts.LibraryId,
Password = accounts.Password
}).FirstOrDefault();
if (qry != null)
{
account = new LibData.Model.AccountDC();
account = qry;
}
}
return account;
}
}
public partial class LibDataEntities
{
public static string ConnectionString;
public LibDataEntities(string connectionString) : base(connectionString)
{
}
}
public Startup(IHostingEnvironment env)
{
// Set connection string in Manager Project
LibData.Manager.Entities.LibDataEntities.ConnectionString = Configuration.GetConnectionString("LibDataEntities");
}
是否可以与类库管理器交互而不必重载连接字符串(例如下面的示例)?
using (var db = new LibDataEntities())
FWIW:我不想重载连接字符串的原因是因为这个类库被非asp.netcore应用程序使用,其中Web.Config已经包含连接字符串。
以下是我尝试的一些新代码但没有成功(如下面的回复中所示:
public void ConfigureServices(IServiceCollection services)
{
services.AddDistributedMemoryCache();
services.AddSession();
services.AddAuthorization();
services.AddMvc(options =>
{
options.Filters.Add(new ExceptionFilter());
});
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddMvcGrid();
services.AddScoped(_ => new AccountManager());
services.AddScoped<LibDataEntities>(_ => new LibDataEntities(Configuration.GetConnectionString("LibDataEntities")));
}
private readonly AccountManager _am;
public HomeController(AccountManager am)
{
_am = am;
}
来自控制器:
LibData.Model.AccountDC account = _am.AuthenticateAccount(lvm.Email, lvm.Password);